UNPKG

1.21 kBJavaScriptView Raw
1
2const _ = require('lodash');
3const async = require('async');
4const uuidV4 = require('uuid').v4;
5
6const cache = require('../cache');
7
8const NS = 'cacheflash';
9
10//
11module.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 // clear flash scope
21 req.session.flash = {};
22 req.session.cacheflash = [];
23 }
24
25 // save flash data in session
26 req.flash = function(key, value) {
27 req.session.flash[key] = value;
28 };
29
30 // save flash data in redis
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); // 60s
37 }
38
39 if (!cacheflash.length) {
40 return next();
41 }
42
43 // async load cacheflash objects
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};