-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.js
174 lines (164 loc) · 5.03 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
'use strict';
const async = require('async');
const redis = require('redis');
const url = require('url');
/**
* @module express-view-cache
*/
/**
* @class EVC
* @classdesc
* This class accepts redis connection parameters as constructor, and builds Caching Middleware
* by method { link EVC#cachingMiddleware }
* @see EVC#cachingMiddleware
*/
function EVC(options) {
let config = {};
let redisClient;
let o;
if (typeof options === 'string') {
o = url.parse(options);
if (o.protocol === 'redis:') {
config.host = o.hostname || 'localhost';
config.port = o.port || 6379;
config.pass = o.auth ? o.auth.split(':')[1] : null;
config.appPort = process.env.PORT || 3000;
} else {
throw new Error('ExpressViewCache - unable to parse ' + o + ' as redis connection string!');
}
} else {
config = {
'host': options.host || 'localhost',
'port': options.port || 6379,
'pass': options.pass,
'client': options.client,
};
}
redisClient = config.client || redis.createClient(config.port, config.host, {
'auth_pass': config.pass,
'return_buffers': false
});
/**
* @method EVC#customCachingMiddleware
* @param {function} extractKeyName(req, function extractKeyNameCallback(error, key, ttl){...}){...}
* @return {function} function(req, res, next){...}
*/
this.customCachingMiddleware = function (extractKeyName) {
return function (req, res, next) {
if (req.method === 'GET') { // only GET responses are cached
let ended = false;
let data = {};
let ttl;
let needle;
async.waterfall([
function (cb){
extractKeyName(req, function (error, k, t){
if(error) {
return cb(error);
}
ttl = t;
cb(null, k);
});
},
function (key,cb) {
async.parallel({
'dataFound': function (clb) {
redisClient.hgetall(key, clb);
},
'age': function (clb) {
needle = key;
redisClient.ttl(key, clb);
}
}, function (error, obj) {
if (error) {
cb(error);
} else {
cb(null, obj.dataFound, obj.age);
}
});
},
function (dataFound, age, cb) {
if (dataFound) {
res.set('Expires', new Date(Date.now() + age).toUTCString());
res.set('Last-Modified', new Date(dataFound.savedAt).toUTCString());
res.set('Content-Type', dataFound.contentType);
res.status(dataFound.statusCode);
res.end(dataFound.content);
ended = true;
return cb(null, true);
}
// generating data
const buffer = [];
const original = res.write;
res.write = (...a) => {
buffer.push(`${a[0]}`);
original.apply(res, a);
};
const end = res.end;
res.end = (...a) => {
if (a[0]) {
buffer.push(`${a[0]}`);
}
data.Expires = new Date(Date.now() + ttl).toUTCString();
data['Last-Modified'] = new Date().toUTCString();
data['Content-Type'] = res.getHeaders()['content-type'];
data.statusCode = res.statusCode;
data.content = buffer.join('');
res.set('Expires', data.Expires);
res.set('Last-Modified', new Date());
end.apply(res, a);
cb(null, false);
};
next();
},
function (hit, cb) {
if (hit) {
cb(null);
} else {
async.series([
function (clb) {
redisClient.hmset(needle, {
'savedAt': new Date(),
'contentType': data['Content-Type'],
'statusCode': data.statusCode,
'content': data.content,
}, clb);
},
function (clb) {
redisClient.expire(needle, Math.floor(ttl / 1000), clb);
}
], cb);
}
}
], function (error){
if(error) {
return next(error);
}
if(!ended) {
next();
}
});
} else {
next();
}
};
};
/**
* @method EVC#cachingMiddleware
* @param {Number} [ttlInMilliSeconds=30000]
* @return {function} function(req, res, next){...}
*/
this.cachingMiddleware = function (ttlInMilliSeconds) {
const ttl = parseInt(ttlInMilliSeconds, 10) || 30000;
if(!ttl) {
throw new Error(`error parsing ${ttlInMilliSeconds} as positive integer`);
}
return this.customCachingMiddleware(function (req, cb){
return cb(null, req.originalUrl, ttl);
});
};
return this;
}
module.exports = exports = function (config) {
return new EVC(config);
};