-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
73 lines (67 loc) · 1.7 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
import * as idbKeyVal from 'idb-keyval'
const defaultOpts = { maxAge: Infinity, version: 0, lib: idbKeyVal }
const getOpts = passedOptions => Object.assign({}, defaultOpts, passedOptions)
export const keyValLib = idbKeyVal
export const get = (key, opts, store) => {
const { maxAge, version, lib } = getOpts(opts)
return lib
.get(key, store)
.then(JSON.parse)
.then(parsed => {
const age = Date.now() - parsed.time
if (age > maxAge || version !== parsed.version) {
lib.del(key, store)
return null
}
return parsed.data
})
.catch(() => null)
}
export const set = (key, data, spec, store) => {
const { lib, version } = getOpts(spec)
return lib
.set(
key,
JSON.stringify({
version,
time: Date.now(),
data,
}),
store
)
.catch(() => null)
}
export const getAll = (spec, store) => {
const opts = getOpts(spec)
let keys
return opts.lib
.keys(store)
.then(retrievedKeys => {
keys = retrievedKeys
return Promise.all(keys.map(key => get(key, opts, store)))
})
.then(data =>
data.reduce((acc, bundleData, index) => {
if (bundleData) {
acc[keys[index]] = bundleData
}
return acc
}, {})
)
.catch(() => {})
}
export const getConfiguredCache = spec => {
const opts = getOpts(spec)
let store
if (opts.name) {
store = idbKeyVal.createStore(opts.name, opts.name)
}
return {
get: key => get(key, opts, store),
set: (key, val) => set(key, val, opts, store),
getAll: () => getAll(opts, store),
del: key => opts.lib.del(key, store),
clear: () => opts.lib.clear(store),
keys: () => opts.lib.keys(store),
}
}