Open History to see the last commit
1import AsyncStorage from '@react-native-async-storage/async-storage'
2import type { StorageAdapter } from '@tanstack/offline-transactions'
3
4/**
5 * AsyncStorage adapter for React Native offline transactions.
6 * Implements the StorageAdapter interface using @react-native-async-storage/async-storage.
7 */
8export class AsyncStorageAdapter implements StorageAdapter {
9 private prefix: string
10
11 constructor(prefix = `offline-tx:`) {
12 this.prefix = prefix
13 }
14
15 private getKey(key: string): string {
16 return `${this.prefix}${key}`
17 }
18
19 async get(key: string): Promise<string | null> {
20 return AsyncStorage.getItem(this.getKey(key))
21 }
22
23 async set(key: string, value: string): Promise<void> {
24 await AsyncStorage.setItem(this.getKey(key), value)
25 }
26
27 async delete(key: string): Promise<void> {
28 await AsyncStorage.removeItem(this.getKey(key))
29 }
30
31 async keys(): Promise<Array<string>> {
32 const allKeys = await AsyncStorage.getAllKeys()
33 return allKeys
34 .filter((k) => k.startsWith(this.prefix))
35 .map((k) => k.slice(this.prefix.length))
36 }
37
38 async clear(): Promise<void> {
39 const keys = await this.keys()
40 const prefixedKeys = keys.map((k) => this.getKey(k))
41 if (prefixedKeys.length > 0) {
42 await AsyncStorage.multiRemove(prefixedKeys)
43 }
44 }
45}