]>
Commit | Line | Data |
---|---|---|
0bd78bf3 C |
1 | // Thanks: https://github.com/capaj/localstorage-polyfill |
2 | ||
3 | const valuesMap = new Map() | |
4 | ||
5 | class MemoryStorage { | |
6 | [key: string]: any | |
7 | [index: number]: string | |
8 | ||
244b4ae3 | 9 | getItem (key: any) { |
0bd78bf3 C |
10 | const stringKey = String(key) |
11 | if (valuesMap.has(key)) { | |
12 | return String(valuesMap.get(stringKey)) | |
13 | } | |
14 | ||
15 | return null | |
16 | } | |
17 | ||
244b4ae3 | 18 | setItem (key: any, val: any) { |
0bd78bf3 C |
19 | valuesMap.set(String(key), String(val)) |
20 | } | |
21 | ||
244b4ae3 | 22 | removeItem (key: any) { |
0bd78bf3 C |
23 | valuesMap.delete(key) |
24 | } | |
25 | ||
26 | clear () { | |
27 | valuesMap.clear() | |
28 | } | |
29 | ||
30 | key (i: any) { | |
31 | if (arguments.length === 0) { | |
32 | throw new TypeError('Failed to execute "key" on "Storage": 1 argument required, but only 0 present.') | |
33 | } | |
34 | ||
35 | const arr = Array.from(valuesMap.keys()) | |
36 | return arr[i] | |
37 | } | |
38 | ||
39 | get length () { | |
40 | return valuesMap.size | |
41 | } | |
42 | } | |
43 | ||
44 | let peertubeLocalStorage: Storage | |
88a7f93f | 45 | let peertubeSessionStorage: Storage |
0bd78bf3 C |
46 | try { |
47 | peertubeLocalStorage = localStorage | |
88a7f93f | 48 | peertubeSessionStorage = sessionStorage |
0bd78bf3 C |
49 | } catch (err) { |
50 | const instance = new MemoryStorage() | |
51 | ||
88a7f93f | 52 | peertubeLocalStorage = sessionStorage = new Proxy(instance, { |
e80687c4 | 53 | set: function (obj, prop: string | number, value) { |
0bd78bf3 C |
54 | if (MemoryStorage.prototype.hasOwnProperty(prop)) { |
55 | instance[prop] = value | |
56 | } else { | |
57 | instance.setItem(prop, value) | |
58 | } | |
59 | return true | |
60 | }, | |
e80687c4 | 61 | get: function (target, name: string | number) { |
0bd78bf3 C |
62 | if (MemoryStorage.prototype.hasOwnProperty(name)) { |
63 | return instance[name] | |
64 | } | |
65 | if (valuesMap.has(name)) { | |
66 | return instance.getItem(name) | |
67 | } | |
68 | } | |
69 | }) | |
70 | } | |
71 | ||
88a7f93f RK |
72 | export { |
73 | peertubeLocalStorage, | |
74 | peertubeSessionStorage | |
75 | } |