This repository has been archived on 2022-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
IcyNet.eu/scripts/flash.js

44 lines
1.1 KiB
JavaScript
Raw Normal View History

2017-08-02 21:24:01 +00:00
const util = require('util')
const format = util.format
/*
* Clean version of https://github.com/jaredhanson/connect-flash
* Included here to avoid includng ridiculously small modules
*/
module.exports = function (options) {
options = options || {}
2020-05-28 18:30:21 +00:00
const safe = (options.unsafe === undefined) ? true : !options.unsafe
2017-08-02 21:24:01 +00:00
return function (req, res, next) {
if (req.flash && safe) { return next() }
req.flash = _flash
next()
}
}
function _flash (type, msg) {
if (this.session === undefined) throw Error('req.flash() requires sessions')
2020-05-28 18:30:21 +00:00
const msgs = this.session.flash = this.session.flash || {}
2017-08-02 21:24:01 +00:00
if (type && msg) {
if (arguments.length > 2 && format) {
2020-05-28 18:30:21 +00:00
const args = Array.prototype.slice.call(arguments, 1)
2017-08-02 21:24:01 +00:00
msg = format.apply(undefined, args)
} else if (Array.isArray(msg)) {
msg.forEach((val) => {
(msgs[type] = msgs[type] || []).push(val)
})
return msgs[type].length
}
return (msgs[type] = msgs[type] || []).push(msg)
} else if (type) {
2020-05-28 18:30:21 +00:00
const arr = msgs[type]
2017-08-02 21:24:01 +00:00
delete msgs[type]
return arr || []
} else {
this.session.flash = {}
return msgs
}
}