How to use the koa function in koa

To help you get started, we’ve selected a few koa 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 outline / outline / server / app.js View on Github external
referrerPolicy,
} from 'koa-helmet';
import logger from 'koa-logger';
import mount from 'koa-mount';
import enforceHttps from 'koa-sslify';
import Koa from 'koa';
import bugsnag from 'bugsnag';
import onerror from 'koa-onerror';
import updates from './utils/updates';

import auth from './auth';
import api from './api';
import emails from './emails';
import routes from './routes';

const app = new Koa();

app.use(compress());

if (process.env.NODE_ENV === 'development') {
  /* eslint-disable global-require */
  const convert = require('koa-convert');
  const webpack = require('webpack');
  const devMiddleware = require('koa-webpack-dev-middleware');
  const hotMiddleware = require('koa-webpack-hot-middleware');
  const config = require('../webpack.config.dev');
  const compile = webpack(config);
  /* eslint-enable global-require */

  app.use(
    convert(
      devMiddleware(compile, {
github jeffijoe / snicket / examples / simple-cqrs-es-inventory / api.ts View on Github external
)
Dispatcher.register(
  'CheckIn',
  CommandHandlers.makeCheckInHandler(store)
)
Dispatcher.register(
  'Remove',
  CommandHandlers.makeRemoveHandler(store)
)
Dispatcher.register(
  'Deactivate',
  CommandHandlers.makeDeactivateHandler(store)
)

// Set up a Koa app to expose our awesome app to the world.
const app = new Koa()
app.use(bodyParser())
app.use(async (ctx: any, next: any) => {
  try {
    await next()
  } catch (err) {
    ctx.status = 500
    ctx.body = {
      error: err.message
    }
    logger.error('Error in request', err)
  }
})

const controller = {
  // Writes
  async createItem(ctx: any) {
github liaisonjs / liaison / packages / layer-http-server / src / layer-http-server.js View on Github external
_createKoa() {
    const koa = new Koa();

    koa.use(
      logger(message => {
        debug(message);
      })
    );
    koa.use(jsonError());
    koa.use(cors({maxAge: 900})); // 15 minutes
    koa.use(bodyParser({enableTypes: ['json'], jsonLimit: '8mb'}));

    koa.use(async ctx => {
      if (ctx.method !== 'POST') {
        throw new Error('Invalid HTTP request');
      }

      const layer = await this._layerCreator();
github unix / cobot / examples / koa / index.ts View on Github external
import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import cobot, { BotEvents } from '../../src'


const app: Koa = new Koa()
app.use(bodyParser())
app.use(cobot.koa())

const bot = cobot.lift({
  host: 'https://gitlab.xxxx.com/',
  private: 'xxx',
})
bot.on(BotEvents.WikiOnAnyAction, async (context) => {
  console.log(context.object_attributes.action)
})

app.listen(3000, () => {
  console.log('koa example server listening on 3000.')
})
github zalando-incubator / tessellate / packages / tessellate-server / src / TessellateServer.js View on Github external
constructor(options: Options = {}) {
    this.app = new Koa();
    this.app.name = options.name;
    this.router = new RxRouter();
    this.metrics = new MetricsApp().app;
    this.middleware = [];

    const morganFormat = String(nconf.get('MORGAN_FORMAT'));
    const morganThresh = parseInt(nconf.get('MORGAN_THRESHOLD'));
    const morganSkip = (req: IncomingMessage, res: ServerResponse) => res.statusCode < morganThresh;

    this.app
      .use(morgan(morganFormat, { skip: morganSkip }))
      .use(error())
      .use(bodyParser({ enableTypes: ['json'] }))
      .use(additionalMiddleware(this.middleware))
      .use(this.router.routes())
      .use(this.router.allowedMethods());
github hojas / vblog / server / src / app.js View on Github external
async function start() {
  await connectMongo()

  const app = new Koa()
  app.use(bodyParser())
  app.use(json())
  app.use(cors())

  const router = new Router()
  routers(router)

  app.listen(3000)
}
github poetapp / node / src / EthereumRegistryWriter / Router.ts View on Github external
export const Router = ({
  dependencies: {
    logger,
    messaging,
    business,
    ethereumRegistryContract,
  },
  configuration: {
    apiPort,
    exchange,
  },
}: Arguments): Router => {
  const routerLogger = childWithFileName(logger, __filename)
  const koa = new Koa()
  const koaRouter = new KoaRouter()
  let server: Server

  const start = async () => {
    await messaging.consume(exchange.claimIpfsHash, onClaimIPFSHash)
    await messaging.consume(exchange.batchCreated, onBatchCreated)
    await messaging.consumeBlockDownloaded(onPoetBlockAnchorsDownloaded)
    await messaging.consumeClaimsDownloaded(onClaimsDownloaded)
    await messaging.consume(exchange.batchRead, onBatchRead)

    const handleEventError = (error: any, event: any) => {
      if (error)
        logger.error({ error, event })
    }

    const onCidAddedPromievent = await ethereumRegistryContract.onCidAdded({}, handleEventError)
github chenbin92 / koa2-webpack-boilerplate / src / index.js View on Github external
import Koa from 'koa';
import path from 'path';
import render from 'koa-ejs';
import serve from 'koa-static';
import webpack from 'webpack';
import { devMiddleware, hotMiddleware } from 'koa-webpack-middleware';
import webpackConfig from '../build/webpack.config';
import router from './router';
import { chalkInfo } from '../build/chalkConfig';

const compiler = webpack(webpackConfig);

const port = process.env.HTTP_PORT || 3000;
const ip = process.env.HTTP_IP || undefined;
const app = new Koa();

app.use(serve(path.resolve(__dirname, './public')));
render(app, {
  root: path.join(__dirname, 'view'),
  layout: 'layout/index',
  viewExt: 'html',
  cache: false,
  debug: process.env.NODE_ENV !== 'production',
});
app.use(router().routes()).use(router().allowedMethods());
app.use(devMiddleware(compiler, {
  watchOptions: {
    aggregateTimeout: 300,
    poll: true,
  },
  reload: true,
github ddellamico / ionic-conference-api / src / server.js View on Github external
* @author    Damien Dell'Amico 
 * @copyright Copyright (c) 2016
 * @license   GPL-3.0
 */

'use strict';

import Koa from 'koa';
import logger from 'koa-logger';
import mount from 'koa-mount';
import serve from 'koa-static';
import api from './api';
import middleware from './middleware';
import config from './config';

const app = new Koa();
if (config.environment === 'development') {
  app.use(logger());
}
app.use(middleware());
app.use(mount(api));
app.use(serve(`${process.cwd()}/docs`));

export { app };
github cdebotton / react-universal / app / admin / src / index.js View on Github external
import serve from 'koa-static';
import compress from 'koa-compress';
import mount from 'koa-mount';
import proxy from 'koa-proxy';
import Jade from 'koa-jade';
import { format } from 'util';

import {
  paths,
  host as HOST,
  webpackPort as WEBPACK_PORT,
  __DEV__,
  __PROD__,
} from '../config';

export const app = koa();
const { middleware: jade } = new Jade({
  viewPath: path.resolve(__dirname, 'views'),
});

const statsPath: string = path.resolve(
  __dirname,
  '..',
  'dist',
  'webpack-stats.json'
);
let stats: {[key: string]: Array} = { css: [], js: [] };

if (__PROD__) {
  stats = require(statsPath);
  app.use(compress());
}

koa

Koa web app framework

MIT
Latest version published 29 days ago

Package Health Score

95 / 100
Full package analysis