-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
253 lines (222 loc) · 7.58 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
'use strict'
var Promise = require('es6-promise').Promise
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var rmdir = require('rimraf')
var crypto = require('crypto')
module.exports = function (options) {
// check args
if (typeof options !== 'object') {
throw new Error('options of type object expected')
}
if (typeof options.cachePath !== 'string') {
throw new Error('option cachePath of type string expected')
}
// check for existing cache folder, if not found, create folder, then resolve
function initCache (cachePath) {
return new Promise(function (resolve, reject) {
mkdirp(cachePath, function (err) {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
function serialize (val) {
var circRefColl = []
return JSON.stringify(val, function (name, value) {
if (typeof value === 'function') {
return // ignore arguments and attributes of type function silently
}
if (typeof value === 'object' && value !== null) {
if (circRefColl.indexOf(value) !== -1) {
// circular reference found, discard key
return
}
// store value in collection
circRefColl.push(value)
}
return value
})
}
function getCacheFilePath (fn, args, opt) {
var salt = opt.salt || ''
var fnStr = (opt.noBody ? '' : String(fn))
var argsStr
var hash
argsStr = serialize(args)
hash = crypto.createHash('md5').update(fnStr + argsStr + salt).digest('hex')
return path.join(options.cachePath, opt.cacheId, hash)
}
function memoizeFn (fn, opt) {
function checkOptions (optExt) {
if (optExt.salt && typeof optExt.salt !== 'string') {
throw new Error('salt option of type string expected, got \'' + typeof optExt.salt + '\'')
}
if (optExt.cacheId && typeof optExt.cacheId !== 'string') {
throw new Error('cacheId option of type string expected, got \'' + typeof optExt.cacheId + '\'')
}
if (optExt.maxAge && typeof optExt.maxAge !== 'number') {
throw new Error('maxAge option of type number bigger zero expected')
}
}
if (opt && typeof opt !== 'object') {
throw new Error('opt of type object expected, got \'' + typeof opt + '\'')
}
var optExt = opt || {}
if (typeof fn !== 'function') {
throw new Error('fn of type function expected')
}
checkOptions(optExt)
optExt.cacheId = optExt.cacheId || './'
function resolveWithMemFn () {
return new Promise(function (resolve) {
var memFn = function () {
var args = Array.prototype.slice.call(arguments)
var fnaCb = args.length ? args[args.length - 1] : undefined
if (typeof fnaCb === 'function' && fnaCb.length > 0) {
optExt.async = true
}
return new Promise(function (resolve, reject) {
var filePath = getCacheFilePath(fn, args, optExt)
function cacheAndReturn () {
var result
function writeResult (r, cb) {
var resultObj,
resultString
if ((r && typeof r === 'object') || typeof r === 'string') {
resultObj = {data: r}
resultString = serialize(resultObj)
} else {
resultString = '{"data":' + r + '}'
}
if (optExt.maxAge) {
setTimeout(function () {
fs.unlink(filePath, function (err) {
if (err && err.code !== 'ENOENT') {
throw err
}
})
}, optExt.maxAge)
}
fs.writeFile(filePath, resultString, cb)
}
function processFnAsync () {
args.pop()
args.push(function (/* err, result... */) {
var cbErr = arguments[0]
var cbArgs = Array.prototype.slice.call(arguments)
cbArgs.shift()
if (cbErr) {
// if we have an exception we don't cache anything
return reject(cbErr)
}
cbArgs.unshift(null)
writeResult(cbArgs, function () {
resolve(fnaCb.apply(null, cbArgs))
})
})
fn.apply(null, args)
}
function processFn () {
try {
result = fn.apply(null, args)
} catch (e) {
return reject(e)
}
if (result && result.then && typeof result.then === 'function') {
// result is a promise instance
return result.then(function (retObj) {
writeResult(retObj, function () {
resolve(retObj)
})
},
function (err) {
// if we have an exception we don't cache anything
reject(err)
})
} else {
writeResult(result, function (err) {
if (err) {
reject(err)
} else {
resolve(result)
}
})
}
}
if (optExt.async) {
return processFnAsync()
}
return processFn()
}
fs.readFile(filePath, {encoding: 'utf8'}, function (err, data) {
if (err) {
return cacheAndReturn()
}
function parseResult (resultString) {
try {
return JSON.parse(resultString).data // will fail on NaN
} catch (e) {
return undefined
}
}
function retrieveAndReturn () {
function processFnAsync () {
resolve(fnaCb.apply(null, parseResult(data)))
}
function processFn () {
resolve(parseResult(data))
}
if (optExt.async) {
return processFnAsync()
}
return processFn()
}
if (optExt.force) {
delete optExt.force
// result has not been cached yet or needs to be recached - cache and return it!
cacheAndReturn()
} else {
// result has already been cached - return it!
retrieveAndReturn()
}
})
})
}
resolve(memFn)
})
}
return initCache(path.join(options.cachePath, optExt.cacheId)).then(resolveWithMemFn)
}
function invalidateCache (cacheId) {
return new Promise(function (resolve, reject) {
if (cacheId && typeof cacheId !== 'string') {
reject(Error('cacheId option of type string expected, got \'' + typeof cacheId + '\''))
} else {
var cachPath = cacheId ? path.join(options.cachePath, cacheId) : options.cachePath
rmdir(cachPath, function (err) {
if (err) {
reject(err)
} else {
resolve()
}
})
}
})
}
var cache = initCache(options.cachePath)
return {
'fn': function (fn, opt) {
return cache.then(function () {
return memoizeFn(fn, opt)
}, function (err) {
throw err
})
},
'invalidate': invalidateCache
}
}