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