-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
201 lines (177 loc) · 5.65 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
'use strict'
const LruStore = require('./lruStore')
const debug = require('debug')('route-cache')
const queues = Object.create(null)
const defaults = {
max: 64 * 1000000, // ~64mb
length: function (n, key) {
if (n.body && typeof n.body === 'string') {
return n.body.length
}
return 1
},
maxAge: 200 // deletes stale cache older than 200ms
}
let cacheStore = new LruStore(defaults)
module.exports.config = function (opts) {
if (opts) {
if (opts.max) {
defaults.max = opts.max
}
if (opts.cacheStore) {
cacheStore = opts.cacheStore
} else {
cacheStore = new LruStore(defaults)
}
module.exports.cacheStore = cacheStore
}
return this
}
function drainQueue (key) {
debug('drainQueue:', key)
let subscriber = null
while (queues[key] && queues[key].length > 0) {
subscriber = queues[key].shift()
process.nextTick(subscriber)
}
delete queues[key]
}
module.exports.cacheSeconds = function (secondsTTL, cacheKey) {
const ttl = secondsTTL * 1000
return function (req, res, next) {
let key = req.originalUrl // default cache key
if (typeof cacheKey === 'function') {
key = cacheKey(req, res) // dynamic key
// Allow skipping the cache
if (!key) { return next() }
} else if (typeof cacheKey === 'string') {
key = cacheKey // custom key
}
cacheStore.get('redirect:' + key).then((redirectKey) => {
if (redirectKey) {
res.redirect(redirectKey.status, redirectKey.url)
return true
}
return false
}).then((handledByRedirect) => {
if (handledByRedirect) return true
return cacheStore.get(key).then((value) => {
if (value) {
// returns the value immediately
debug('hit!!', key)
if (value.isJson) {
res.status(value.status).json(value.body)
} else {
res.status(value.status).send(value.body)
}
return true
}
return false
})
}).then((handledByCache) => {
if (handledByCache) return true
res.original_send = res.send
res.original_end = res.end
res.original_json = res.json
res.original_redirect = res.redirect
if (!queues[key]) {
queues[key] = []
}
let didHandle = false
function rawSend (data, isJson) {
debug('rawSend', typeof data, data ? data.length : 0)
// pass-through for Buffer - not supported
if (typeof data === 'object') {
if (Buffer.isBuffer(data)) {
queues[key] = [] // clear queue
res.set('Content-Length', data.length)
res.original_send(data)
return
}
}
didHandle = true
const body = data instanceof Buffer ? data.toString() : data
if (res.statusCode < 400) cacheStore.set(key, { status: res.statusCode, body: body, isJson: isJson }, ttl)
// send this response to everyone in the queue
drainQueue(key)
if (isJson) {
debug('res.original_json')
res.original_json(body)
} else {
debug('res.original_send')
res.original_send(body)
}
}
// first request will get rendered output
if (queues[key].length === 0) {
debug('miss:', key)
queues[key].push(function noop () {})
didHandle = false
res.send = function (data) {
// debug('res.send() >>', data.length)
if (didHandle) {
res.original_send(data)
} else {
rawSend(data, false)
}
}
res.end = (data) => {
res.original_end(data)
drainQueue(key)
}
res.json = function (data) {
rawSend(data, true)
}
// If response happens to be a redirect -- store it to redirect all subsequent requests.
res.redirect = function (url) {
let address = url
let status = 302
// allow statusCode for 301 redirect. See: https://github.com/expressjs/express/blob/master/lib/response.js#L857
if (arguments.length === 2) {
if (typeof arguments[0] === 'number') {
status = arguments[0]
address = arguments[1]
} else {
console.log('res.redirect(url, status): Use res.redirect(status, url) instead')
status = arguments[1]
}
}
cacheStore.set('redirect:' + key, { url: address, status: status }, ttl)
res.original_redirect(status, address)
return drainQueue(key)
}
next()
// subsequent requests will batch while the first computes
} else {
debug(key, '>> has queue.length:', queues[key].length)
queues[key].push(function () {
cacheStore.get('redirect:' + key)
.then((redirectKey) => {
if (redirectKey) {
res.redirect(redirectKey.status, redirectKey.url)
return true
}
return false
})
.then((handledByRedirect) => {
if (handledByRedirect) return
return cacheStore.get(key).then((cachedValue) => {
const value = cachedValue || {}
debug('>> queued hit:', key, value.length)
if (value.isJson) {
res.status(value.status || 200).json(value.body)
} else {
res.status(value.status || 200).send(value.body)
}
})
})
})
}
})
}
}
module.exports.removeCache = function (url) {
cacheStore.del('redirect:' + url)
cacheStore.del(url)
}
module.exports.cacheStore = cacheStore