-
-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathcreateMMKV.web.ts
54 lines (50 loc) · 1.68 KB
/
createMMKV.web.ts
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
/* global localStorage */
import type { MMKVConfiguration, NativeMMKV } from 'react-native-mmkv';
const canUseDOM =
typeof window !== 'undefined' && window.document?.createElement != null;
export const createMMKV = (config: MMKVConfiguration): NativeMMKV => {
if (config.id !== 'mmkv.default') {
throw new Error("MMKV: 'id' is not supported on Web!");
}
if (config.encryptionKey != null) {
throw new Error("MMKV: 'encryptionKey' is not supported on Web!");
}
if (config.path != null) {
throw new Error("MMKV: 'path' is not supported on Web!");
}
const storage = () => {
if (!canUseDOM) {
throw new Error(
'Tried to access storage on the server. Did you forget to call this in useEffect?'
);
}
const domStorage =
global?.localStorage ?? window?.localStorage ?? localStorage;
if (domStorage == null) {
throw new Error(`Could not find 'localStorage' instance!`);
}
return domStorage;
};
return {
clearAll: () => storage().clear(),
delete: (key) => storage().removeItem(key),
set: (key, value) => storage().setItem(key, value.toString()),
getString: (key) => storage().getItem(key) ?? undefined,
getNumber: (key) => {
const value = storage().getItem(key);
if (value == null) return undefined;
return Number(value);
},
getBoolean: (key) => {
const value = storage().getItem(key);
if (value == null) return undefined;
return value === 'true';
},
getAllKeys: () => Object.keys(storage()),
contains: (key) => storage().getItem(key) != null,
trim: () => {},
recrypt: () => {
throw new Error('`recrypt(..)` is not supported on Web!');
},
};
};