-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathstaticFileEtags.js
48 lines (40 loc) · 1.28 KB
/
staticFileEtags.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
'use strict';
const etag = require('etag')
, fs = require('fs')
, events = require('harken')
, not = require('./tools').not
, isDefined = require('./tools').isDefined
, files = {}
, addEtag = (fileIn) => {
fs.readFile(fileIn, (err, data) => {
if (err) {
events.emit('error', {
message: 'could not read file'
, error: err
, file: fileIn
});
} else {
files[fileIn] = etag(data);
events.emit(`etag:get:${fileIn}`, files[fileIn]);
}
});
}
, isValid = (etagObj, etagged) => {
return isDefined(etagObj.etag)
&& etagged
&& files[etagObj.file] === etagObj.etag;
}
, checkEtag = (etagObj) => {
const etagged = isDefined(files[etagObj.file])
, valid = isValid(etagObj, etagged);
// if the file hasn't been etagged then etag it
if (not(etagged)) {
addEtag(etagObj.file);
} else {
events.emit(`etag:get:${etagObj.file}`, files[etagObj.file]);
}
events.emit(`etag:check:${etagObj.file}`, valid);
};
events.on('etag:check', checkEtag);
events.on('etag:add', addEtag);
events.on('etag:update', addEtag);