I've got a super simple Koa app (v2) that looks like this:
const Koa = require('koa');
const app = new Koa();
// Tag some output on to the end so I can see the app context.
app.use(async function (context, next) {
context.body = '';
await next();
context.body += JSON.stringify(context, undefined, 2);
console.log(JSON.stringify(app));
});
// Response generation.
app.use(async function (context, next) {
if (context.request.url === '/') {
context.body = 'Document root.';
} else {
context.body = 'Bad path: ' + context.request.url ;
}
await next();
});
app.listen(3000);
It works exactly as I would expect. I understand all the async/await elements, no problem.
As an educational exercise, I'm trying to write an app "from scratch" that simply handles some routes and serves up some content (perhaps from a database, depending on get params, etc.).
Since it is an educational exercise, I do not want to use existing middleware.
I'm stuck right now on understanding how to pass data downstream and upstream. For example, let's say I want some middleware that parses URL params:
// This goes right before the Response generation middleware.
app.use(async function (context, next) {
var params = parseParams(context.request.url);
await next();
});
How do I get the params data passed into the next middleware? Since context is defined as a const in the Koa source code, I can't change by doing things like:
...
context.request.urlParams = parseParams(context.request.url);
...
When the context is accessed 'downstream', modifications don't stick (aside from changing string values like .body
or .request.url
).
I don't think I can simply define an external app state and pass it into the middleware function because other middleware (e.g. packages found in npm) don't seem to have some expectation of being passed in an app state param at generation time.
I think I'm missing some key concept in this paradigm. Any help?
via Sir Robert