UNPKG

1.81 kBJavaScriptView Raw
1/**
2 * Get uppy instance IDs for which state is stored.
3 */
4function findUppyInstances () {
5 const instances = []
6 for (let i = 0; i < localStorage.length; i++) {
7 const key = localStorage.key(i)
8 if (/^uppyState:/.test(key)) {
9 instances.push(key.slice('uppyState:'.length))
10 }
11 }
12 return instances
13}
14
15/**
16 * Try to JSON-parse a string, return null on failure.
17 */
18function maybeParse (str) {
19 try {
20 return JSON.parse(str)
21 } catch (err) {
22 return null
23 }
24}
25
26let cleanedUp = false
27module.exports = class MetaDataStore {
28 constructor (opts) {
29 this.opts = Object.assign({
30 expires: 24 * 60 * 60 * 1000 // 24 hours
31 }, opts)
32 this.name = `uppyState:${opts.storeName}`
33
34 if (!cleanedUp) {
35 cleanedUp = true
36 MetaDataStore.cleanup()
37 }
38 }
39
40 /**
41 *
42 */
43 load () {
44 const savedState = localStorage.getItem(this.name)
45 if (!savedState) return null
46 const data = maybeParse(savedState)
47 if (!data) return null
48
49 // Upgrade pre-0.20.0 uppyState: it used to be just a flat object,
50 // without `expires`.
51 if (!data.metadata) {
52 this.save(data)
53 return data
54 }
55
56 return data.metadata
57 }
58
59 save (metadata) {
60 const expires = Date.now() + this.opts.expires
61 const state = JSON.stringify({
62 metadata,
63 expires
64 })
65 localStorage.setItem(this.name, state)
66 }
67
68 /**
69 * Remove all expired state.
70 */
71 static cleanup () {
72 const instanceIDs = findUppyInstances()
73 const now = Date.now()
74 instanceIDs.forEach((id) => {
75 const data = localStorage.getItem(`uppyState:${id}`)
76 if (!data) return null
77 const obj = maybeParse(data)
78 if (!obj) return null
79
80 if (obj.expires && obj.expires < now) {
81 localStorage.removeItem(`uppyState:${id}`)
82 }
83 })
84 }
85}