peterforgacs
2/3/2018 - 3:01 PM

[Koa routing] How to pipe koa steps and routers #koa #koarouter #node.js #javascript

[Koa routing] How to pipe koa steps and routers #koa #koarouter #node.js #javascript

'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}.`);
});

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.