-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathetag.js
68 lines (53 loc) · 1.21 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict'
var crypto = require('crypto')
var etagCache = require('./etag-cache.json')
module.exports = etag
function etag (entity, opts) {
if (Object(entity) === entity) {
opts = entity
entity = opts.entity
}
var error = false
opts = opts || {}
opts.algorithm = opts.algorithm || 'md5'
opts.encoding = opts.encoding || 'utf8'
opts.output = opts.output || 'base64'
var match
Object.keys(etagCache).forEach(function (k) {
match = (etagCache[k].algorithm === opts.algorithm &&
etagCache[k].encoding === opts.encoding &&
etagCache[k].output === opts.output &&
entity === Buffer.from(etagCache[k].content.data).toString()) &&
k
})
if (match) { return match }
var hash
try {
hash = crypto
.createHash(opts.algorithm)
.update(entity, opts.encoding)
} catch (e) {
error = true
}
if (!opts.output || opts.output === 'base64') {
try {
hash = hash
.digest('base64')
.replace(/=+$/, '')
} catch (e) {
error = true
}
if (!error) {
return hash
}
}
try {
hash = hash.digest(opts.output)
} catch (e) {
error = true
}
if (error) {
return Error('oh oh')
}
return hash
}