Skip to content

Instantly share code, notes, and snippets.

@peterforgacs
Last active February 3, 2018 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterforgacs/b5110c01649c6c9c68124d4f45b96e0d to your computer and use it in GitHub Desktop.
Save peterforgacs/b5110c01649c6c9c68124d4f45b96e0d to your computer and use it in GitHub Desktop.
[Koa routing] How to pipe koa steps and routers #koa #koarouter #node.js #javascript

Koa

Uses middleware pattern.
Each time we use app.use we add an other middleware function.

ctx - The context contains all the information for a signle request and the response object aswell.

next - Calls the next middleware.

The order is sequential.
The router methods order depends on where we add:

app
.use(router.routes())
.use(router.allowedMethods());

If its after the "general" methods they run first and then get passed.

'use strict';
const Koa = require('koa');
const KoaBodyParser = require('koa-bodyparser');
const KoaRouter = require('koa-router');
const app = new Koa();
const router = new KoaRouter();
app
.use(KoaBodyParser())
// x-response-time
app.use(async (ctx, next) => {
console.log('first');
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
console.log(ctx);
});
// logger
app.use(async (ctx, next) => {
console.log('second');
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
// response
app.use(async (ctx, next) => {
console.log('third');
ctx.body = 'Hello World';
await next();
});
// router
router.get('/', (ctx, next) => {
// ctx.router available
console.log('router working');
next();
});
app
.use(router.routes())
.use(router.allowedMethods());
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}.`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment