-
Notifications
You must be signed in to change notification settings - Fork 0
/
etag.js
45 lines (35 loc) · 905 Bytes
/
etag.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
'use strict';
const {createHash} = require('crypto');
const rgxNoCache = /(?:^|,)\s*?no-cache\s*?(?:,|$)/;
function onSend(req, res, body, next) {
if (
res.statusCode !== 200 ||
req.headers['cache-control'] !== undefined && rgxNoCache.test(req.headers['cache-control'])
) {
next();
return;
}
let {etag} = res.headers;
if (etag === undefined) {
if (typeof body !== 'string' && body instanceof Buffer === false) {
next();
return;
}
const hash = createHash('sha1')
.update(body, 'utf8')
.digest('base64')
.slice(0, 27);
etag = '"' + body.length.toString(36) + '-' + hash + '"';
res.headers.etag = etag;
}
if (req.headers['if-none-match'] === etag) {
res.statusCode = 304;
next(null, null);
} else {
next();
}
}
function etagPlugin(app) {
app.addHook('onSend', onSend);
}
module.exports = etagPlugin;