mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import AsyncStorage from '@react-native-async-storage/async-storage'
2
3import {logger} from '#/logger'
4import {
5 defaults,
6 Schema,
7 tryParse,
8 tryStringify,
9} from '#/state/persisted/schema'
10import {PersistedApi} from './types'
11
12export type {PersistedAccount, Schema} from '#/state/persisted/schema'
13export {defaults} from '#/state/persisted/schema'
14
15const BSKY_STORAGE = 'BSKY_STORAGE'
16
17let _state: Schema = defaults
18
19export async function init() {
20 const stored = await readFromStorage()
21 if (stored) {
22 _state = stored
23 }
24}
25init satisfies PersistedApi['init']
26
27export function get<K extends keyof Schema>(key: K): Schema[K] {
28 return _state[key]
29}
30get satisfies PersistedApi['get']
31
32export async function write<K extends keyof Schema>(
33 key: K,
34 value: Schema[K],
35): Promise<void> {
36 _state = {
37 ..._state,
38 [key]: value,
39 }
40 await writeToStorage(_state)
41}
42write satisfies PersistedApi['write']
43
44export function onUpdate<K extends keyof Schema>(
45 _key: K,
46 _cb: (v: Schema[K]) => void,
47): () => void {
48 return () => {}
49}
50onUpdate satisfies PersistedApi['onUpdate']
51
52export async function clearStorage() {
53 try {
54 await AsyncStorage.removeItem(BSKY_STORAGE)
55 } catch (e: any) {
56 logger.error(`persisted store: failed to clear`, {message: e.toString()})
57 }
58}
59clearStorage satisfies PersistedApi['clearStorage']
60
61async function writeToStorage(value: Schema) {
62 const rawData = tryStringify(value)
63 if (rawData) {
64 try {
65 await AsyncStorage.setItem(BSKY_STORAGE, rawData)
66 } catch (e) {
67 logger.error(`persisted state: failed writing root state to storage`, {
68 message: e,
69 })
70 }
71 }
72}
73
74async function readFromStorage(): Promise<Schema | undefined> {
75 let rawData: string | null = null
76 try {
77 rawData = await AsyncStorage.getItem(BSKY_STORAGE)
78 } catch (e) {
79 logger.error(`persisted state: failed reading root state from storage`, {
80 message: e,
81 })
82 }
83 if (rawData) {
84 return tryParse(rawData)
85 }
86}