I would like to monkey patch express's res.json() and res.render() to combine the object with flashes and errors. So i could do this:
res.flash('error', 'You suck!');
res.formError('moneyInput', 'Give me more!');
... later
res.json({success: false});
and it would return:
{flashes: [{error: 'You suck!'}], errors: [{'moneyInput': 'Give me more!'}], content: {success: false}}
and likewise res.render would stick those things into locals for the template.
So right now - monkey patching seems like the best course. I plan to monkeypatch it in a middleware.
Questions:
Is there a better alternative?
Has anyone else done this?
What are the pitfalls ? (other than having to update my code every time i upgrade express)
One alternative it to store the pending data on the response object but not monkey patch the methods in there:
function flash (res, type, message) { //stick this in a shared module
res._flash = {};
res._flash[type] = message;
return res;
}
//in some handler function
flash(res, 'error', 'You suck!');
However, I would say for a small number of really useful functions, just monkey patch it and take the risk. It is already convention to dynamically add data fields to the response which is where res.body comes when using the bodyParser middleware, for example. If you want to be paranoid about name collisions, just add a prefix like res._mkFlash.