I have one method that helps responding to requests. Its signature is as follows:
function render(req, res, data, kind, route)
It is being called dozens of times with different parameters. I would like to have a cleaner code where I would call
render(data, kind, route) knowing that req and res are always there in the context when calling.
As the following
router.get('/', async function (req, res, next) {
// some logic
// render({}, 'kind', 'route') instead of
render(req, res, {}, 'kind', 'route')
Following @deceze advice. I ended up using a middleware that is attaching a closure as the following
const makeRenderer = (req, res, next) => {
res.locals.renderer = (data, kind, route) => renderer(req, res, data, kind, route)
next()
}
router.get('/', makeRenderer, async function (req, res, next) {
const listings = await mongoQueries.getDocumentsSince(
20, '', req.body.pagination)
const { page, perPage } = req.body.pagination
const data = {
listings: listings.documents,
addressPoints: [],
current: page,
pages: Math.ceil(listings.count / perPage)
}
res.locals.renderer(data, 'listings', 'listings')
})