Created
January 29, 2017 13:45
-
-
Save adam-cyclones/326c2795182694502fdd71ce111922a5 to your computer and use it in GitHub Desktop.
Inject / Intercepting Express 4 res.render with ES6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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