|
| 1 | +import type { AsyncStorage } from "@react-native-async-storage/async-storage"; |
| 2 | + |
| 3 | +class AsyncStorageMemoryImpl implements AsyncStorage { |
| 4 | + private store = new Map<string, string>(); |
| 5 | + |
| 6 | + getItem = async (key: string): Promise<string | null> => { |
| 7 | + return this.store.get(key) ?? null; |
| 8 | + }; |
| 9 | + |
| 10 | + setItem = async (key: string, value: string): Promise<void> => { |
| 11 | + this.store.set(key, value); |
| 12 | + }; |
| 13 | + |
| 14 | + removeItem = async (key: string): Promise<void> => { |
| 15 | + this.store.delete(key); |
| 16 | + }; |
| 17 | + |
| 18 | + getMany = async (keys: string[]): Promise<Record<string, string | null>> => { |
| 19 | + return keys.reduce<Record<string, string | null>>((result, key) => { |
| 20 | + result[key] = this.store.get(key) ?? null; |
| 21 | + return result; |
| 22 | + }, {}); |
| 23 | + }; |
| 24 | + |
| 25 | + setMany = async (entries: Record<string, string>): Promise<void> => { |
| 26 | + for (const [key, value] of Object.entries(entries)) { |
| 27 | + this.store.set(key, value); |
| 28 | + } |
| 29 | + }; |
| 30 | + |
| 31 | + removeMany = async (keys: string[]): Promise<void> => { |
| 32 | + for (const key of keys) { |
| 33 | + this.store.delete(key); |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + getAllKeys = async (): Promise<string[]> => { |
| 38 | + return Array.from(this.store.keys()); |
| 39 | + }; |
| 40 | + |
| 41 | + clear = async (): Promise<void> => { |
| 42 | + this.store.clear(); |
| 43 | + }; |
| 44 | +} |
| 45 | + |
| 46 | +const inMemoryDbRegistry = new Map<string, AsyncStorageMemoryImpl>(); |
| 47 | + |
| 48 | +export function createAsyncStorage(databaseName: string): AsyncStorage { |
| 49 | + if (!inMemoryDbRegistry.has(databaseName)) { |
| 50 | + inMemoryDbRegistry.set(databaseName, new AsyncStorageMemoryImpl()); |
| 51 | + } |
| 52 | + return inMemoryDbRegistry.get(databaseName)!; |
| 53 | +} |
| 54 | + |
| 55 | +export function clearAllMockStorages(): void { |
| 56 | + inMemoryDbRegistry.clear(); |
| 57 | +} |
| 58 | + |
| 59 | +export default createAsyncStorage("legacy"); |
0 commit comments