-
Notifications
You must be signed in to change notification settings - Fork 84
/
caching.js
76 lines (52 loc) · 1.48 KB
/
caching.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
76
/** internal
* mixin Caching
*
* An internal mixin whose public methods are exposed on the [[Environment]]
* and [[Index]] classes.
**/
////////////////////////////////////////////////////////////////////////////////
'use strict';
// stdlib
var join = require('path').join;
var crypto = require('crypto');
// internal
var Asset = require('../assets/asset');
////////////////////////////////////////////////////////////////////////////////
function expandKey(self, key) {
key = String(key).replace(self.root, '');
key = crypto.createHash('md5').update(key, 'utf8').digest('hex');
return join('mincer', key);
}
function cacheSet(self, key, hash) {
hash._version = self.digest.digest('hex');
self.cache.set(expandKey(self, key), hash);
}
function cacheGet(self, key) {
var hash = self.cache.get(expandKey(self, key));
if (hash && hash._version === self.digest.digest('hex')) {
return hash;
}
}
module.exports.cacheAsset = function (path, fn) {
var asset, hash;
if (!this.cache) {
return fn();
}
asset = Asset.fromHash(this, cacheGet(this, path));
if (asset && asset.isFresh(this)) {
return asset;
}
asset = fn();
if (asset) {
hash = {};
asset.encodeWith(hash);
// Save the asset to its path
cacheSet(this, path, hash);
// Since path maybe a logical or full pathname, save the
// asset its its full path too
if (path !== asset.pathname) {
cacheSet(this, asset.pathname, hash);
}
return asset;
}
};