-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
76 lines (65 loc) · 2.09 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
module.exports = class HtmlCache {
constructor(cacheDir = global.scriptPath + '/cache', cacheKey = '-cache') {
this.md5 = require('md5');
this.fs = require('fs');
this.shouldSave = false;
this.cacheKey = cacheKey;
this.cacheDir = cacheDir;
}
getCacheKey(url, type = 'html') {
return this.cacheDir + '/' + this.md5(url) + this.cacheKey + '.' + type;
}
exists(url) {
return this.fs.existsSync(this.getCacheKey(url));
}
get(url) {
/** TODO: need to check when file was created and delete it if it's expired */
let key = this.getCacheKey(url);
return new Promise((resolve, reject) => {
if (this.exists(url)) {
this.fs.readFile(key, (error, buf) => {
error ? reject(error) : resolve(buf.toString());
});
} else {
reject('Cache does not exist (' + url + ') (' + key + ')');
}
});
}
save(url, content) {
return new Promise((resolve, reject) => {
this.fs.writeFile(this.getCacheKey(url), content, (error) => {
error ? reject(error) : resolve();
});
});
}
}
let cache = new Cache();
module.exports = {
requestReceived: (req, res, next) => {
if (req.prerender.renderType === 'html') {
if (cache.exists(req.prerender.url)) {
console.log('Cache: hit');
cache.get(req.prerender.url).then((content) => {
res.send(200, content);
});
} else {
console.log('Cache: miss');
cache.shouldSave = true;
next();
}
} else {
next();
}
},
pageLoaded: (req, res, next) => {
if (cache.shouldSave === true) {
console.log('Cache: saving');
cache.save(req.prerender.url, req.prerender.content).then(() => {
cache.shouldSave = false;
next();
});
} else {
next();
}
}
};