diff --git a/lib/flash.js b/lib/flash.js index a278bc1..039ef7a 100644 --- a/lib/flash.js +++ b/lib/flash.js @@ -14,7 +14,7 @@ var isArray = require('util').isArray; module.exports = function flash(options) { options = options || {}; var safe = (options.unsafe === undefined) ? true : !options.unsafe; - + return function(req, res, next) { if (req.flash && safe) { return next(); } req.flash = _flash; @@ -58,7 +58,7 @@ module.exports = function flash(options) { */ function _flash(type, msg) { if (this.session === undefined) throw Error('req.flash() requires sessions'); - var msgs = this.session.flash = this.session.flash || {}; + var msgs = this.session.flash || {}; if (type && msg) { // util.format is available in Node.js 0.6+ if (arguments.length > 2 && format) { @@ -68,15 +68,24 @@ function _flash(type, msg) { msg.forEach(function(val){ (msgs[type] = msgs[type] || []).push(val); }); + this.session.flash = msgs; return msgs[type].length; } - return (msgs[type] = msgs[type] || []).push(msg); + var ret = (msgs[type] = msgs[type] || []).push(msg); + this.session.flash = msgs; + return ret; } else if (type) { var arr = msgs[type]; - delete msgs[type]; + if (Array.isArray(arr)) { + delete msgs[type]; + } + if (Object.getOwnPropertyNames(msgs).length === 0) { + delete this.session.flash; + } else { + this.session.flash = msgs; + } return arr || []; } else { - this.session.flash = {}; return msgs; } }