-
-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathMMKV.ts
246 lines (227 loc) · 6.37 KB
/
MMKV.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import { createMMKV } from './createMMKV';
import { createMockMMKV } from './createMMKV.mock';
import { isJest } from './PlatformChecker';
interface Listener {
remove: () => void;
}
/**
* Used for configuration of a single MMKV instance.
*/
export interface MMKVConfiguration {
/**
* The MMKV instance's ID. If you want to use multiple instances, make sure to use different IDs!
*
* @example
* ```ts
* const userStorage = new MMKV({ id: `user-${userId}-storage` })
* const globalStorage = new MMKV({ id: 'global-app-storage' })
* ```
*
* @default 'mmkv.default'
*/
id: string;
/**
* The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization:
*
* @example
* ```ts
* const temporaryStorage = new MMKV({ path: '/tmp/' })
* ```
*/
path?: string;
/**
* The MMKV instance's encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV.
*
* Encryption keys can have a maximum length of 16 bytes.
*
* @example
* ```ts
* const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })
* ```
*/
encryptionKey?: string;
}
/**
* Represents a single MMKV instance.
*/
interface MMKVInterface {
/**
* Set a value for the given `key`.
*/
set: (key: string, value: boolean | string | number) => void;
/**
* Get the boolean value for the given `key`, or `undefined` if it does not exist.
*
* @default undefined
*/
getBoolean: (key: string) => boolean | undefined;
/**
* Get the string value for the given `key`, or `undefined` if it does not exist.
*
* @default undefined
*/
getString: (key: string) => string | undefined;
/**
* Get the number value for the given `key`, or `undefined` if it does not exist.
*
* @default undefined
*/
getNumber: (key: string) => number | undefined;
/**
* Checks whether the given `key` is being stored in this MMKV instance.
*/
contains: (key: string) => boolean;
/**
* Delete the given `key`.
*/
delete: (key: string) => void;
/**
* Get all keys.
*
* @default []
*/
getAllKeys: () => string[];
/**
* Delete all keys.
*/
clearAll: () => void;
/**
* Trim unused space on the storage file
*/
trim: () => void;
/**
* Sets (or updates) the encryption-key to encrypt all data in this MMKV instance with.
*
* To remove encryption, pass `undefined` as a key.
*
* Encryption keys can have a maximum length of 16 bytes.
*/
recrypt: (key: string | undefined) => void;
/**
* Adds a value changed listener. The Listener will be called whenever any value
* in this storage instance changes (set or delete).
*
* To unsubscribe from value changes, call `remove()` on the Listener.
*/
addOnValueChangedListener: (
onValueChanged: (key: string) => void
) => Listener;
}
export type NativeMMKV = Pick<
MMKVInterface,
| 'clearAll'
| 'contains'
| 'delete'
| 'getAllKeys'
| 'getBoolean'
| 'getNumber'
| 'getString'
| 'set'
| 'trim'
| 'recrypt'
>;
const onValueChangedListeners = new Map<string, ((key: string) => void)[]>();
/**
* A single MMKV instance.
*/
export class MMKV implements MMKVInterface {
private nativeInstance: NativeMMKV;
private functionCache: Partial<NativeMMKV>;
private id: string;
/**
* Creates a new MMKV instance with the given Configuration.
* If no custom `id` is supplied, `'mmkv.default'` will be used.
*/
constructor(configuration: MMKVConfiguration = { id: 'mmkv.default' }) {
this.id = configuration.id;
this.nativeInstance = isJest()
? createMockMMKV()
: createMMKV(configuration);
this.functionCache = {};
}
private get onValueChangedListeners() {
if (!onValueChangedListeners.has(this.id)) {
onValueChangedListeners.set(this.id, []);
}
return onValueChangedListeners.get(this.id)!;
}
private getFunctionFromCache<T extends keyof NativeMMKV>(
functionName: T
): NativeMMKV[T] {
if (this.functionCache[functionName] == null) {
this.functionCache[functionName] = this.nativeInstance[functionName];
}
return this.functionCache[functionName] as NativeMMKV[T];
}
private onValuesChanged(keys: string[]) {
if (this.onValueChangedListeners.length === 0) return;
for (const key of keys) {
for (const listener of this.onValueChangedListeners) {
listener(key);
}
}
}
set(key: string, value: boolean | string | number): void {
const func = this.getFunctionFromCache('set');
func(key, value);
this.onValuesChanged([key]);
}
getBoolean(key: string): boolean | undefined {
const func = this.getFunctionFromCache('getBoolean');
return func(key);
}
getString(key: string): string | undefined {
const func = this.getFunctionFromCache('getString');
return func(key);
}
getNumber(key: string): number | undefined {
const func = this.getFunctionFromCache('getNumber');
return func(key);
}
contains(key: string): boolean {
const func = this.getFunctionFromCache('contains');
return func(key);
}
delete(key: string): void {
const func = this.getFunctionFromCache('delete');
func(key);
this.onValuesChanged([key]);
}
getAllKeys(): string[] {
const func = this.getFunctionFromCache('getAllKeys');
return func();
}
clearAll(): void {
const keys = this.getAllKeys();
const func = this.getFunctionFromCache('clearAll');
func();
this.onValuesChanged(keys);
}
recrypt(key: string | undefined): void {
const func = this.getFunctionFromCache('recrypt');
return func(key);
}
trim(): void {
const func = this.getFunctionFromCache('trim');
return func();
}
toString(): string {
return `MMKV (${this.id}): [${this.getAllKeys().join(', ')}]`;
}
toJSON(): object {
return {
[this.id]: this.getAllKeys(),
};
}
addOnValueChangedListener(onValueChanged: (key: string) => void): Listener {
this.onValueChangedListeners.push(onValueChanged);
return {
remove: () => {
const index = this.onValueChangedListeners.indexOf(onValueChanged);
if (index !== -1) {
this.onValueChangedListeners.splice(index, 1);
}
},
};
}
}