How to use koa-views - 10 common examples

To help you get started, we’ve selected a few koa-views examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github leidenglai / React-Koa2-SSR / server / server.prod.js View on Github external
import router from './routes'

import './middlewares/mongooseLog'
import './models'

import './models/redisClient'

// 设置全局变量
global.__DEV__ = false
global.__PROD__ = true

global.__COMPONENT_DEVTOOLS__ = false

const port = process.env.port || 7000

app.use(views(path.resolve(__dirname, '../views/prod'), { map: { html: 'ejs' } }))
app.use(serve(path.resolve(__dirname, '../dist/client')))
app.use(clientRoute)
app.use(router.routes())
app.use(packBody) // 处理body返回
app.use(router.allowedMethods())
app.use(handle404) // 处理404
app.listen(port)

console.log(`\n==> 🌎  Listening on port ${port}. Open up http://localhost:${port}/ in your browser.\n`)
github rupertqin / koa2-netease-cloudmusic / src / app.js View on Github external
const _use = app.use
app.use = x => _use.call(app, convert(x))


// middlewares
app.use(bodyparser())
app.use(json())
app.use(logger())

// static
app.use(koaStatic(path.join(__dirname, '../public'), {
  pathPrefix: ''
}))

// views
app.use(views(path.join(__dirname, '../views'), {
  extension: 'ejs'
}))

// 500 error
koaOnError(app, {
  template: 'views/500.ejs'
})

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
github lubien / koa-react-redux-universal-boilerplate / server / app.js View on Github external
app.use(convert(session({
  store: new MongoStore({
    url: config.MONGO_URL,
  }),
})));

// Passport
import passport from './lib/passport';
import loggedInMiddleware from './lib/logged-in-middleware';
app.use(passport.initialize());
app.use(passport.session());
app.use(loggedInMiddleware());

// Views
import views from 'koa-views';
app.use(views(path.join(__dirname, 'views/'), {
  extension: 'pug',
}));

// Routes
import routes from './routes/';
routes.map(
  route => app
    .use(route.middleware())
    .use(route.allowedMethods())
);

// Mongoose
import mongoose from 'mongoose';
mongoose.connect(config.MONGO_URL);
const db = mongoose.connection;
db.on('error', console.log.bind(console, 'DB Error:'));
github muffin / server / routes / front.js View on Github external
const getPartials = () => {
  let partials = {}

  // fs-extra already has a walker but it's asynchronous
  const partialFiles = walkSync(partialDir)

  // Assign partials
  for (let partial of partialFiles) {
    let name = path.parse(partial).name
    partials[name] = 'partials/' + name
  }

  return partials
}

router.use(views(viewDir, {
  extension: 'hbs',
  map: {
    hbs: 'handlebars'
  }
}))

router.use(async (ctx, next) => {
  let pages = false

  try {
    pages = await Page.find().sort({ _id: 1 })
  } catch (err) {
    log('Couldn\'t load pages', err)
  }

  if (!pages) {
github Canner / canner / packages / cms-server / src / server / app.ts View on Github external
await next();
      } catch (err) {
        this.logger.fatal({
          message: err.message,
          stacktrace: err.stack,
        });
        const errorCode = (err.isBoom && err.data && err.data.code) ? err.data.code : 'INTERNAL_ERROR';
        const statusCode =
          (err.isBoom && err.output && err.output.statusCode) ? err.output.statusCode : err.status || 500;

        ctx.status = statusCode;
        ctx.body = {code: errorCode, message: err.message};
      }
    });

    router.use(views(path.join(__dirname, './views'), {
      extension: 'pug'
    }));

    // serve client static
    const clientStatic = serve(this.config.staticsPath, this.config.clientBundledDir);
    router.get(clientStatic.path, loggingMiddleware, clientStatic.middleware);

    // serve favicon
    const faviconPath = path.resolve(__dirname, '../public/favicon');
    const favicon = serve('/public/favicon', faviconPath);
    router.get(favicon.path, loggingMiddleware, favicon.middleware);

    // cms
    const setConfigMiddleware = async (ctx: Context, next: () => Promise) => {
      // put into frontendConfig
      const username = ctx.cookies.get(usernameCookieKey, {signed: true});
github bamlab / bam-api / src / koa / server.js View on Github external
app.use(koaBody());

// use the loging middleware, to log request and log special event
// override koa's undocumented error handler
app.context.onerror = () => {};
// specify that this is our api
app.context.api = true;
// use our logger middleware
app.use(logger());

app.use(knexMiddleware(knex));

// use the ect template string for views
import path from 'path';
app.use(
  koaViews(path.join(__dirname, 'views'), {
    map: {
      html: 'ect',
    },
  })
);

const engine = new Engine({
  engineConfig: { apiKey: 'service:tychota-Bam-Api:1Z3thyxiVF84L4nF97NUmw' },
  graphqlPort: 3000, // GraphQL port
  endpoint: '/graphql', // GraphQL endpoint suffix - '/graphql' by default
  dumpTraffic: true,
});
engine.start();

// configure jwt middleware to connect to auth0, check the token and
const jwtConfig = {
github larsha / bolaget.io / services / web / src / web.js View on Github external
// 404
const error404 = {
  error: 'Move along, nothing to see here!'
}

// 500
const error500 = {
  error: 'Ouch, an ugly error has occured!'
}

const app = new Koa()

// Logs information
app.use(koaLogger())

app.use(views(__dirname, {
  extension: 'hbs',
  map: {
    hbs: 'handlebars'
  }
}))

// Handle errors
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    ctx.status = err.status || 500
    ctx.body = err.status === 404 ? error404 : error500
  }
})
github embbnux / kails / app / index.js View on Github external
app.use(cacheMiddle());

app.use(bodyParser());
app.use(methodOverride((req, _res) => {
  if (req.body && (typeof req.body === 'object') && ('_method' in req.body)) {
    // look in urlencoded POST bodies and delete it
    const method = req.body._method;
    delete req.body._method;
    return method;
  }
}));
app.use(convert(json()));
app.use(convert(logger()));

//views with pug
app.use(views(__dirname + '/views', { extension: 'pug' }));

// catch error
app.use(middlewares.catchError);

// csrf
app.use(new CSRF({
  invalidSessionSecretMessage: 'Invalid session secret',
  invalidSessionSecretStatusCode: 403,
  invalidTokenMessage: 'Invalid CSRF token',
  invalidTokenStatusCode: 403,
  excludedMethods: [ 'GET', 'HEAD', 'OPTIONS' ],
  disableQuery: false
}));

// add helpers for views
app.use(middlewares.addHelper);
github AwesomeLogos / awesome-logos / src / server.ts View on Github external
const status = ctx.status || 404;
        if (status === 404) {
            ctx.status = 404;
            await ctx.render('404.hbs', { title: '404', h1: '404 - Page not found', url: ctx.req.url });
        }
    } catch (err) {
        ctx.status = 500;
        await ctx.render('500.hbs', { title: 'Server Error', message: err.message });
    }
});

app.use(KoaStatic("static"));
app.use(KoaMount('/logos', KoaStatic("logos")));


app.use(KoaViews(path.join(__dirname, '..', 'views'), {
    map: { hbs: 'handlebars' },
    options: {
        helpers: {
            'addCommas': function (num:number) {
                return num.toLocaleString();
            },
            'equals': function(a:any, b:any, block:any) {
                return a == b ? block.fn() : '';
            },
            'for': function(from:number, to:number, incr:number, block:any) {
                let result = '';
                for (let loop = from; loop < to; loop += incr)
                    result += block.fn(loop);
                return result;
            },
            'isPageVisible': function(page:number, currentPage:number, maxPage:number, block:any) {

koa-views

Template rendering middleware for koa

MIT
Latest version published 9 months ago

Package Health Score

50 / 100
Full package analysis

Popular koa-views functions