-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstow.js
86 lines (76 loc) · 1.89 KB
/
stow.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
module.exports = {
createCache: function createCache (Backend, options) {
return new Cache(Backend, options)
},
Cache: Cache
}
function Cache (Backend, options) {
var opts = options || {}
opts.ttl = opts.ttl || 0
this.backend = new Backend(opts)
}
Cache.prototype.set = function (key, data, ttl, tags, cb) {
var options = {}
// Support set(options, cb) style calling.
if (typeof key !== 'string') {
Object.keys(key).forEach(function (k) {
options[k] = key[k]
})
cb = data
// Parse arguments.
} else {
options.key = key
options.data = data
if (typeof ttl === 'function') {
cb = ttl
} else if (typeof tags === 'function') {
cb = tags
if (typeof ttl === 'number') {
options.ttl = ttl
} else {
options.tags = ttl
}
} else {
options.ttl = ttl
options.tags = tags
}
}
if (typeof options.key === 'undefined') {
return cb(new Error('No key passed to cache.set()'))
}
if (typeof options.data === 'undefined') {
return cb(new Error('No data passed to cache.set()'))
}
if (options.tags) {
options.tags = this.flattenTags(options.tags)
}
this.backend.set(options, cb)
}
Cache.prototype.get = function (key, cb) {
this.backend.get(key, cb)
}
Cache.prototype.invalidate = function (tags, cb) {
this.backend.invalidate(this.flattenTags(tags), cb)
}
Cache.prototype.clear = function (pattern, cb) {
if (typeof pattern === 'function') {
cb = pattern
pattern = '*'
}
this.backend.clear(pattern, cb)
}
Cache.prototype.flattenTags = function (tags) {
if (Array.isArray(tags)) {
return tags
}
var norm = []
Object.keys(tags).forEach(function (key) {
(Array.isArray(tags[key]) ? tags[key] : [tags[key]]).forEach(function (tag) {
var flat = key + ':' + tag
if (norm.indexOf(flat) < 0) {
norm.push(flat)
}
})
})
return norm
}