Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 598
Megakoresh Avatar asked Nov 20 '25 01:11

Megakoresh


1 Answers

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.

like image 144
Megakoresh Avatar answered Nov 22 '25 17:11

Megakoresh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!