/
index.js
56 lines (44 loc) · 1.06 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
/**
* Module dependencies.
*/
var calculate = require('etag');
var Stream = require('stream');
var fs = require('mz/fs');
/**
* Expose `etag`.
*/
module.exports = etag;
/**
* Add ETag header field.
* @param {object} [options] see https://github.com/jshttp/etag#options
* @param {boolean} [options.weak]
* @return {Function}
* @api public
*/
function etag(options) {
return function *etag(next){
yield next;
// no body
var body = this.body;
if (!body || this.response.get('etag')) return;
// type
var status = this.status / 100 | 0;
// 2xx
if (2 != status) return;
// hash
var etag;
if (body instanceof Stream) {
if (!body.path) return;
var s = yield fs.stat(body.path).catch(noop);
if (!s) return;
etag = calculate(s, options);
} else if (('string' == typeof body) || Buffer.isBuffer(body)) {
etag = calculate(body, options);
} else {
etag = calculate(JSON.stringify(body), options);
}
// add etag
if (etag) this.response.etag = etag;
}
}
function noop() {}