node.js - Best way to add helper methods to context object in Koa2 -


i add method such view , json context object passed controllers. in middleware runs before else:

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

these methods set conventional configuration object (renderer) middleware interprets , renders out actual response setting correct ctx.body. allows me switch template language , have easier time combining api , template requests.

except doesn't work because after await next() ctx.renderer default one, not 1 set controllers. suspect it's namespacing issue, not sure comes from.

what's best practice attach functions context can reference context without being passed them?

ok it's here in docs missed it, docs inside repo , not hosted, makes them hard navigate.

tl;dr: use app.context access context prototype. adding functions there attaches them context object , allows use this within access it.


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -