From c7e9389979e76bbb6e1a9f6f6fb7da97ee12b52d Mon Sep 17 00:00:00 2001 From: wlzch Date: Tue, 24 Jul 2012 21:12:43 +0700 Subject: [PATCH] Implement multiple flash messages support. --- examples/express2/app.js | 5 +++++ examples/express3/app.js | 5 +++++ lib/flash.js | 6 ++++++ test/flash-test.js | 7 +++++++ 4 files changed, 23 insertions(+) diff --git a/examples/express2/app.js b/examples/express2/app.js index c3b83f2..7653249 100644 --- a/examples/express2/app.js +++ b/examples/express2/app.js @@ -32,6 +32,11 @@ app.get('/flash', function(req, res){ res.redirect('/'); }); +app.get('/multiple-flash', function(req, res){ + req.flash('info', ['Welcome', 'Please Enjoy']); + res.redirect('/'); +}); + app.get('/no-flash', function(req, res){ res.redirect('/'); }); diff --git a/examples/express3/app.js b/examples/express3/app.js index 4fb24f7..639786e 100644 --- a/examples/express3/app.js +++ b/examples/express3/app.js @@ -34,4 +34,9 @@ app.get('/no-flash', function(req, res){ res.redirect('/'); }); +app.get('/multiple-flash', function(req, res){ + req.flash('info', ['Welcome', 'Please Enjoy']); + res.redirect('/'); +}); + app.listen(3000); diff --git a/lib/flash.js b/lib/flash.js index f3470ae..d369da5 100644 --- a/lib/flash.js +++ b/lib/flash.js @@ -2,6 +2,7 @@ * Module dependencies. */ var format = require('util').format; +var isArray = require('util').isArray; /** @@ -63,6 +64,11 @@ function _flash(type, msg) { if (arguments.length > 2 && format) { var args = Array.prototype.slice.call(arguments, 1); msg = format.apply(undefined, args); + } else if (isArray(msg)) { + msg.forEach(function(val){ + (msgs[type] = msgs[type] || []).push(val); + }); + return msgs; } return (msgs[type] = msgs[type] || []).push(msg); } else if (type) { diff --git a/test/flash-test.js b/test/flash-test.js index 9d02f80..7f9b904 100644 --- a/test/flash-test.js +++ b/test/flash-test.js @@ -61,6 +61,13 @@ vows.describe('flash').addBatch({ assert.lengthOf(Object.keys(req.session.flash), 1); assert.lengthOf(req.session.flash['info'], 2); }, + 'should set flash messages in one call' : function(err, req, res) { + req.flash('warning', ['username required', 'password required']); + var msgs = req.flash('warning'); + assert.lengthOf(msgs, 2); + assert.equal(msgs[0], 'username required'); + assert.equal(msgs[1], 'password required'); + }, 'should get and clear multiple previously set flash messages' : function(err, req, res) { var msgs = req.flash('info'); assert.lengthOf(msgs, 2);