flash.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * Module dependencies.
  3. */
  4. var format = require('util').format;
  5. var isArray = require('util').isArray;
  6. /**
  7. * Expose `flash()` function on requests.
  8. *
  9. * @return {Function}
  10. * @api public
  11. */
  12. module.exports = function flash(options) {
  13. options = options || {};
  14. var safe = (options.unsafe === undefined) ? true : !options.unsafe;
  15. return function(req, res, next) {
  16. if (req.flash && safe) { return next(); }
  17. req.flash = _flash;
  18. next();
  19. }
  20. }
  21. /**
  22. * Queue flash `msg` of the given `type`.
  23. *
  24. * Examples:
  25. *
  26. * req.flash('info', 'email sent');
  27. * req.flash('error', 'email delivery failed');
  28. * req.flash('info', 'email re-sent');
  29. * // => 2
  30. *
  31. * req.flash('info');
  32. * // => ['email sent', 'email re-sent']
  33. *
  34. * req.flash('info');
  35. * // => []
  36. *
  37. * req.flash();
  38. * // => { error: ['email delivery failed'], info: [] }
  39. *
  40. * Formatting:
  41. *
  42. * Flash notifications also support arbitrary formatting support.
  43. * For example you may pass variable arguments to `req.flash()`
  44. * and use the %s specifier to be replaced by the associated argument:
  45. *
  46. * req.flash('info', 'email has been sent to %s.', userName);
  47. *
  48. * Formatting uses `util.format()`, which is available on Node 0.6+.
  49. *
  50. * @param {String} type
  51. * @param {String} msg
  52. * @return {Array|Object|Number}
  53. * @api public
  54. */
  55. function _flash(type, msg) {
  56. if (this.session === undefined) throw Error('req.flash() requires sessions');
  57. var msgs = this.session.flash = this.session.flash || {};
  58. if (type && msg) {
  59. // util.format is available in Node.js 0.6+
  60. if (arguments.length > 2 && format) {
  61. var args = Array.prototype.slice.call(arguments, 1);
  62. msg = format.apply(undefined, args);
  63. } else if (isArray(msg)) {
  64. msg.forEach(function(val){
  65. (msgs[type] = msgs[type] || []).push(val);
  66. });
  67. return msgs[type].length;
  68. }
  69. return (msgs[type] = msgs[type] || []).push(msg);
  70. } else if (type) {
  71. var arr = msgs[type];
  72. delete msgs[type];
  73. return arr || [];
  74. } else {
  75. this.session.flash = {};
  76. return msgs;
  77. }
  78. }