-
Notifications
You must be signed in to change notification settings - Fork 26
/
squarespace-cache.js
98 lines (72 loc) · 2.43 KB
/
squarespace-cache.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*!
*
* Squarespace cache.
*
*/
var util = require( "./squarespace-util" ),
// Default to unique logger incase setLogger isn't called
logger = require( "node-squarespace-logger" ),
path = require( "path" ),
root = path.join( process.cwd(), ".sqs-cache" ),
noop = function () {},
cache = {},
rJson = /json$/;
// Setup
util.isFile( root, function ( exists ) {
if ( !exists ) {
util.makeDir( root, function () {} );
}
});
// Export
module.exports = {
set: function ( key, val, minify ) {
// Support an optional parameter to optionally minify
// Default if `undefined` is `true` to perform minify
minify = minify === undefined ? true : minify;
logger.log( "cache", ("Store local cache for key => " + key) );
var write = rJson.test( key ) ? util.writeJson : util.writeFile,
value = rJson.test( key ) || !minify ? val : util.packStr( val );
cache[ key ] = value;
write( path.join( root, key ), value, noop );
},
get: function ( key ) {
logger.log( "cache", ("Get local cache for key => " + key) );
return (key ? cache[ key ] : cache);
},
remove: function ( key ) {
logger.log( "cache", ("Remove local cache for key => " + key) );
delete cache[ key ];
util.removeFile( path.join( root, key ), noop );
},
clear: function () {
logger.log( "cache", "Clear local cache" );
cache = {};
util.removeDir( root );
},
preload: function ( cb ) {
util.readDir( root, function ( files ) {
if ( files.length ) {
var total = files.length;
function getFile() {
if ( !files.length ) {
logger.log( "cache", "Preloaded local cache" );
cb();
} else {
var file = files.pop(),
read = rJson.test( file ) ? util.readJson : util.readFile;
read( path.join( root, file ), function ( data ) {
cache[ file ] = rJson.test( file ) ? data : util.packStr( data );
getFile();
});
}
}
getFile();
} else {
cb();
}
});
},
setLogger: function ( lgr ) {
logger = lgr;
}
};