Update index.ts
This commit is contained in:
+8
-11
@@ -1,6 +1,4 @@
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
import getObj from 'lodash.get'
|
||||
import setObj from 'lodash.set'
|
||||
|
||||
import {logger} from '#/logger'
|
||||
import {Schema, PropertyMap} from '#/storage/schema'
|
||||
@@ -16,33 +14,32 @@ let data: Schema | undefined
|
||||
export async function init() {
|
||||
const raw = await AsyncStorage.getItem(STORAGE_ROOT_KEY)
|
||||
logger.debug(`storage initialized`)
|
||||
// TODO: Add try catch here etc, same in lib/storage.ts
|
||||
data = (raw ? JSON.parse(raw) : {}) as Schema
|
||||
}
|
||||
|
||||
export function get<T extends keyof PropertyMap>(keypath: T): PropertyMap[T] {
|
||||
logger.debug(`storage get(${keypath})`)
|
||||
export function get<T extends keyof PropertyMap>(key: T): PropertyMap[T] {
|
||||
logger.debug(`storage get(${key})`)
|
||||
if (!data) {
|
||||
throw new Error(`Data is not initialized. Did you forget to call init()`)
|
||||
}
|
||||
return getObj(data, keypath)
|
||||
return data[key]
|
||||
}
|
||||
|
||||
export async function set<T extends keyof PropertyMap>(
|
||||
keypath: T,
|
||||
key: T,
|
||||
value: PropertyMap[T],
|
||||
) {
|
||||
logger.debug(`storage set(${keypath}, value)`)
|
||||
logger.debug(`storage set(${key}, value)`)
|
||||
if (!data) {
|
||||
throw new Error(`Data is not initialized. Did you forget to call init()`)
|
||||
}
|
||||
data[ley] = value
|
||||
|
||||
const prev = getObj(data, keypath)
|
||||
setObj(data, keypath, value)
|
||||
|
||||
// TODO: actual writing should probably be debounced
|
||||
try {
|
||||
await AsyncStorage.setItem(STORAGE_ROOT_KEY, JSON.stringify(data))
|
||||
} catch (err) {
|
||||
logger.error(`storage set(${keypath}, value) failed`)
|
||||
setObj(data, keypath, prev)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user