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