Skip to content

Instantly share code, notes, and snippets.

@daffl
Created November 12, 2018 01:16
Show Gist options
  • Save daffl/c6cf199b2cc79ed6205b876f081b72d9 to your computer and use it in GitHub Desktop.
Save daffl/c6cf199b2cc79ed6205b876f081b72d9 to your computer and use it in GitHub Desktop.
A Koa middleware example
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
// Store the start time
const start = Date.now();
// Pass to the next middleware and wait for everything to return
await next();
// Calculate the total runtime everything took
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
console.log(`Request to ${ctx.request.url} took ${ms}ms`);
});
app.use(async (ctx, next) => {
// Set response body (will be sent as JSON)
ctx.body = { message: 'Hello world' };
await next();
});
app.use(async (ctx, next) => {
// Add the url to the response body
ctx.body.url = ctx.request.url;
await next();
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment