Skip to content

Instantly share code, notes, and snippets.

@adam-cyclones
Created January 29, 2017 13:45
Show Gist options
  • Save adam-cyclones/326c2795182694502fdd71ce111922a5 to your computer and use it in GitHub Desktop.
Save adam-cyclones/326c2795182694502fdd71ce111922a5 to your computer and use it in GitHub Desktop.
Inject / Intercepting Express 4 res.render with ES6
//custom middlewhare
mount.use( function( req, res, next ) {
//trap any render function call for this mount
res.render = new Proxy(res.render,{
apply(target, thisArg, argumentsList){
//DI data intercept
//BEWARE, i have not added if statements for the potential render arguments
//push a callback
//you could push a data object here.
//you could even catch errors and render that!
argumentsList.push(function(err, html){
//intercept html
console.log(html)
//Lets use cherio to modify the rendered template
let $ = cheerio.load(html)
$('h1').text('Hello there!')
res.send($.html());
})
//retrun modified html
return Reflect.apply(target, thisArg, argumentsList)
}
})
next()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment