简体   繁体   中英

Best way to add helper methods to context object in Koa2

I would like to add method such as view and json to the context object passed to my controllers. I do this in a middleware that runs before everything else:

async function(ctx, next){
  ctx.view = view.bind(ctx);  
  ctx.json = json.bind(ctx);
  await next()
  ctx.renderer.render();
}

these methods set some conventional configuration object (Renderer) that the middleware interprets and then renders out the actual response by setting the correct ctx.body . That allows me to switch template language easily and have an easier time combining API and Template requests.

Except it doesn't work because after await next() the ctx.renderer is the default one, not the one set by controllers. I suspect it's a namespacing issue, but I am not sure where it comes from.

What's the best practice to attach functions to the context that can reference context without it being passed to them?

Ok it's here in the docs I just missed it, the docs are inside a repo and are not hosted, which makes them hard to navigate.

TL;DR: use app.context to access the context prototype. Adding functions there attaches them to the context object and allows you to use this from within to access it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM