Created
November 12, 2018 01:16
-
-
Save daffl/c6cf199b2cc79ed6205b876f081b72d9 to your computer and use it in GitHub Desktop.
A Koa middleware example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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