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

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -