-
Notifications
You must be signed in to change notification settings - Fork 0
/
Storage.js
94 lines (81 loc) · 2.04 KB
/
Storage.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
import Utils from '../../helpers/Utils.js'
class Storage {
constructor(page, storageType) {
if (!['localStorage', 'sessionStorage'].includes(storageType)) {
throw new Error(`localStorage and sessionStorage are the only supported storage types: ${storageType}`)
}
this.page = page
this.storageType = storageType
}
async clear() {
await this.page.evaluate((storageType) => {
window[storageType].clear()
}, this.storageType)
}
async get(name) {
return await this.page.evaluate(
(storageType, name) => {
return window[storageType].getItem(name)
},
this.storageType,
name
)
}
async has(name) {
const names = await this.keys()
return names.includes(name)
}
async items() {
return await this.page.evaluate((storageType) => {
const storage = window[storageType]
const items = {}
Object.keys(storage).forEach(function (key) {
items[key] = storage.getItem(key)
})
return items
}, this.storageType)
}
async keys() {
return await this.page.evaluate((storageType) => {
return Object.keys(window[storageType])
}, this.storageType)
}
async load(jsonFile) {
const json = Utils.readJSON(jsonFile)
for (const key in json) {
await this.set(key, json[key])
}
}
async remove(name) {
await this.page.evaluate(
(storageType, name) => {
window[storageType].removeItem(name)
},
this.storageType,
name
)
}
async set(name, value) {
await this.page.evaluate(
(storageType, name, value) => {
window[storageType].setItem(name, value)
},
this.storageType,
name,
value
)
}
async storageEnabled() {
return await this.page.evaluate((storageType) => {
try {
const uid = new Date()
window[storageType].setItem(uid, uid)
window[storageType].removeItem(uid)
return true
} catch (exception) {
return false
}
}, this.storageType)
}
}
export default Storage