How to use koa-router - 10 common examples

To help you get started, we’ve selected a few koa-router 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 doodooke / doodoo.js / packages / doodoo-plugin-chokidar / lib / index.js View on Github external
decache(path);
        decache(_path.resolve(path));

        // 控制器
        if (isController(path)) {
            const paths = _path.parse(path);
            paths.dir = _.split(paths.dir, "/");
            paths.dir.shift();
            paths.dir = paths.dir.join("/");

            const Ctrl = require(_path.resolve(path));
            if (
                Ctrl instanceof KoaRouter ||
                _.isEqual(
                    Object.keys(Ctrl.__proto__),
                    Object.keys(KoaRouter.prototype)
                )
            ) {
                // 移除旧的
                for (const layer of Ctrl.routes().router.stack) {
                    _.remove(doodoo.router.stack, o => {
                        return o.path === layer.path;
                    });
                }
                return;
            }
            if (!isClass(Ctrl)) {
                return;
            }

            const methods = Object.getOwnPropertyNames(Ctrl.prototype);
            const layers = [];
github Jiasm / notebook / labs / demo / node / learning-koa-router / register / named-router.js View on Github external
})

router.register('/test2', ['GET'], _ => {}, {
  name: 'module'
})

console.log(router.url('module') === '/test1')

try {
  router.register('/test2', ['GET'], null, {
    name: 'error-module'
  })
} catch (e) {
  console.error(e)
}
console.log(Router.route)

app
  .use(router.routes()) // 将该Router对象的中间件注册到Koa实例上,后续请求的主要处理逻辑
  .use(router.allowedMethods()) // 添加针对OPTIONS的响应处理,以及一些METHOD不支持的处理

app.listen(8888, _ => console.log('server run as http://127.0.0.1:8888'))
github wavesplatform / wavesplatform.com / src / server / routes / subdomains.js View on Github external
import Router from 'koa-router';

import { render } from 'src/server/middleware/render';

// page components
import WavesNG from 'src/common/containers/WavesNG';
import WavesNGReducer from 'src/common/containers/WavesNG/reducer';

const subdomains = new Router();

subdomains.get(
  '/waves-ng',
  render({
    script: 'wavesNG',
    component: WavesNG,
    description: 'Help us test Waves-NG',
    reducer: WavesNGReducer,
  })
);

export default subdomains;
github callstack / linaria / website / src / server.js View on Github external
import compress from 'koa-compress';
import send from 'koa-send';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import dedent from 'dedent';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { collect } from 'linaria/server'; // eslint-disable-line import/no-unresolved
import App from './components/App';
import config from '../serve.config';

const cache = {};
const css = fs.readFileSync(path.join(__dirname, '../dist/styles.css'), 'utf8');
const app = new Koa();
const router = new Router();

app.use(compress());

router.get('/', async ctx => {
  const html = ReactDOMServer.renderToStaticMarkup();

  const { critical, other } = collect(html, css);
  const slug = crypto
    .createHash('md5')
    .update(other)
    .digest('hex');

  cache[slug] = other;

  ctx.type = 'html';
  ctx.body = dedent`
github AfterShip / koa-newrelic / index.js View on Github external
};

		try {
			let Koa = require('koa');
			let originalUse = Koa.prototype.use;
			Koa.prototype.use = function (middleware) {
				let wrapped = wrapMiddleware(middleware);
				return originalUse.call(this, wrapped);
			};
			Koa.prototype.use._original = originalUse;
			registerWrapped(Koa.prototype, 'use');

			try {
				const Router = require('koa-router');

				let originalRegister = Router.prototype.register;

				Router.prototype.register = function () {
					let middlewares = Array.isArray(arguments[2]) ? arguments[2] : [arguments[2]];

					let wrappedMiddlewares = middlewares.map(middleware => wrapMiddleware(middleware));

					arguments[2] = wrappedMiddlewares;
					return originalRegister.apply(this, arguments);
				};
				Router.prototype.register._original = originalRegister;
				registerWrapped(Router.prototype, 'register');
			} catch (e) {
				// app didn't use koa-router
			}
		} catch (e) {
			// app didn't use koa
github AfterShip / koa-newrelic / index.js View on Github external
try {
				const Router = require('koa-router');

				let originalRegister = Router.prototype.register;

				Router.prototype.register = function () {
					let middlewares = Array.isArray(arguments[2]) ? arguments[2] : [arguments[2]];

					let wrappedMiddlewares = middlewares.map(middleware => wrapMiddleware(middleware));

					arguments[2] = wrappedMiddlewares;
					return originalRegister.apply(this, arguments);
				};
				Router.prototype.register._original = originalRegister;
				registerWrapped(Router.prototype, 'register');
			} catch (e) {
				// app didn't use koa-router
			}
		} catch (e) {
			// app didn't use koa
			throw new Error('koa-newrelic cannot work without koa');
		}
	}

	// tansaction name
	let parseTransactionName;
	if (opts.customTransactionName && typeof opts.customTransactionName === 'function') {
		parseTransactionName = opts.customTransactionName;
	} else {
		// newrelic has frontend display logic, which will format the transaction name if it's under express
		// (method, path) => 'Expressjs/' + method + '/' + path;
github AfterShip / koa-newrelic / index.js View on Github external
registerWrapped(Koa.prototype, 'use');

			try {
				const Router = require('koa-router');

				let originalRegister = Router.prototype.register;

				Router.prototype.register = function () {
					let middlewares = Array.isArray(arguments[2]) ? arguments[2] : [arguments[2]];

					let wrappedMiddlewares = middlewares.map(middleware => wrapMiddleware(middleware));

					arguments[2] = wrappedMiddlewares;
					return originalRegister.apply(this, arguments);
				};
				Router.prototype.register._original = originalRegister;
				registerWrapped(Router.prototype, 'register');
			} catch (e) {
				// app didn't use koa-router
			}
		} catch (e) {
			// app didn't use koa
			throw new Error('koa-newrelic cannot work without koa');
		}
	}

	// tansaction name
	let parseTransactionName;
	if (opts.customTransactionName && typeof opts.customTransactionName === 'function') {
		parseTransactionName = opts.customTransactionName;
	} else {
		// newrelic has frontend display logic, which will format the transaction name if it's under express
github AfterShip / koa-newrelic / index.js View on Github external
try {
			let Koa = require('koa');
			let originalUse = Koa.prototype.use;
			Koa.prototype.use = function (middleware) {
				let wrapped = wrapMiddleware(middleware);
				return originalUse.call(this, wrapped);
			};
			Koa.prototype.use._original = originalUse;
			registerWrapped(Koa.prototype, 'use');

			try {
				const Router = require('koa-router');

				let originalRegister = Router.prototype.register;

				Router.prototype.register = function () {
					let middlewares = Array.isArray(arguments[2]) ? arguments[2] : [arguments[2]];

					let wrappedMiddlewares = middlewares.map(middleware => wrapMiddleware(middleware));

					arguments[2] = wrappedMiddlewares;
					return originalRegister.apply(this, arguments);
				};
				Router.prototype.register._original = originalRegister;
				registerWrapped(Router.prototype, 'register');
			} catch (e) {
				// app didn't use koa-router
			}
		} catch (e) {
			// app didn't use koa
			throw new Error('koa-newrelic cannot work without koa');
		}
github zerobias / telegram-mtproto / packages / mtproto-beam / src / routes.js View on Github external
//@flow

import Router from 'koa-router'
import client from './client'

const router = Router()

router.post('/invoke/:method', async(ctx) => {
  const method = ctx.params.method || ''
  if (method === '') throw new Error(`Received empty method query`)
  console.log(`Call method ${method}`)
  const args = ctx.request.body || {}
  const result = await client(method, args)
  ctx.body = result
})

export default router
github exomia / cloud / vue / src / api / routes / v1 / directory / delete.js View on Github external
import Router from 'koa-router'
import { deleteDirectory } from '../../../lib/pg/directory'
import { JERROR_INTERNAL_SERVER_ERROR, JERROR_BAD_REQUEST } from '../../../lib/error'

const router = new Router()

router.delete('/:directory_uuid', async ctx => {
    if (!ctx.params.directory_uuid) {
        return JERROR_BAD_REQUEST(ctx, "no 'directory_uuid' specified in the params")
    }

    let result = await deleteDirectory(
        ctx.jwt.payload.email,
        ctx.directory_uuid,
        ctx.request.body.force_delete
    )
    if (!result) {
        return JERROR_INTERNAL_SERVER_ERROR(ctx, 'delete failed')
    }
    ctx.status = 200
    ctx.body = { directory: { uuid: ctx.params.directory_uuid }, error: false }

koa-router

Router middleware for koa. Maintained by Forward Email and Lad.

MIT
Latest version published 2 months ago

Package Health Score

87 / 100
Full package analysis