1 |
|
2 | const _ = require('lodash');
|
3 | const async = require('async');
|
4 | const uuidV4 = require('uuid').v4;
|
5 |
|
6 | const cache = require('../cache');
|
7 |
|
8 | const NS = 'cacheflash';
|
9 |
|
10 |
|
11 | module.exports = function(req, res, next) {
|
12 |
|
13 | req.session.flash = req.session.flash || {};
|
14 | res.locals.flash = req.session.flash;
|
15 |
|
16 | req.session.cacheflash = req.session.cacheflash || [];
|
17 | const cacheflash = req.session.cacheflash;
|
18 |
|
19 | if (req.method === 'GET') {
|
20 |
|
21 | req.session.flash = {};
|
22 | req.session.cacheflash = [];
|
23 | }
|
24 |
|
25 |
|
26 | req.flash = function(key, value) {
|
27 | req.session.flash[key] = value;
|
28 | };
|
29 |
|
30 |
|
31 | req.cacheflash = function(key, value) {
|
32 | const uuid = uuidV4();
|
33 | req.session.cacheflash.push(uuid);
|
34 | const obj = {};
|
35 | obj[key] = value;
|
36 | cache.put(NS, uuid, obj, null, 60);
|
37 | }
|
38 |
|
39 | if (!cacheflash.length) {
|
40 | return next();
|
41 | }
|
42 |
|
43 |
|
44 | async.eachSeries(cacheflash, function(uuid, callback) {
|
45 | cache.get(NS, uuid, function(err, obj) {
|
46 | _.merge(res.locals.flash, obj);
|
47 | callback();
|
48 | });
|
49 | }, function() {
|
50 | next();
|
51 | });
|
52 |
|
53 | };
|