reorg again, absolute (module) imports

This commit is contained in:
austinried
2021-07-08 12:21:44 +09:00
parent a94a011a18
commit ea4421b7af
54 changed files with 186 additions and 251 deletions

View File

@@ -0,0 +1,54 @@
import AsyncStorage from '@react-native-async-storage/async-storage'
export async function getItem(key: string): Promise<any | null> {
try {
const item = await AsyncStorage.getItem(key)
return item ? JSON.parse(item) : null
} catch (e) {
console.error(`getItem error (key: ${key})`, e)
return null
}
}
export async function multiGet(keys: string[]): Promise<[string, any | null][]> {
try {
const items = await AsyncStorage.multiGet(keys)
return items.map(x => [x[0], x[1] ? JSON.parse(x[1]) : null])
} catch (e) {
console.error('multiGet error', e)
return []
}
}
export async function setItem(key: string, item: any): Promise<void> {
try {
await AsyncStorage.setItem(key, JSON.stringify(item))
} catch (e) {
console.error(`setItem error (key: ${key})`, e)
}
}
export async function multiSet(items: string[][]): Promise<void> {
try {
await AsyncStorage.multiSet(items.map(x => [x[0], JSON.stringify(x[1])]))
} catch (e) {
console.error('multiSet error', e)
}
}
export async function getAllKeys(): Promise<string[]> {
try {
return await AsyncStorage.getAllKeys()
} catch (e) {
console.error('getAllKeys error', e)
return []
}
}
export async function multiRemove(keys: string[]): Promise<void> {
try {
await AsyncStorage.multiRemove(keys)
} catch (e) {
console.error('multiRemove error', e)
}
}

View File

@@ -0,0 +1,10 @@
import { atomWithStorage } from 'jotai/utils'
import { getItem, setItem } from '@app/storage/asyncstorage'
export default <T>(key: string, defaultValue: T) => {
return atomWithStorage<T>(key, defaultValue, {
getItem: async () => (await getItem(key)) || defaultValue,
setItem: setItem,
delayInit: true,
})
}

38
app/storage/music.ts Normal file
View File

@@ -0,0 +1,38 @@
import { DownloadedSong } from '@app/models/music'
import { getItem, multiGet, multiSet } from '@app/storage/asyncstorage'
const key = {
downloadedSongKeys: '@downloadedSongKeys',
downloadedAlbumKeys: '@downloadedAlbumKeys',
downloadedArtistKeys: '@downloadedArtistKeys',
downloadedPlaylistKeys: '@downloadedPlaylistKeys',
}
export async function getDownloadedSongs(): Promise<DownloadedSong[]> {
const keysItem = await getItem(key.downloadedSongKeys)
const keys: string[] = keysItem ? JSON.parse(keysItem) : []
const items = await multiGet(keys)
return items.map(x => {
const parsed = JSON.parse(x[1] as string)
return {
id: x[0],
type: 'song',
...parsed,
}
})
}
export async function setDownloadedSongs(items: DownloadedSong[]): Promise<void> {
await multiSet([
[key.downloadedSongKeys, JSON.stringify(items.map(x => x.id))],
...items.map(x => [
x.id,
JSON.stringify({
name: x.name,
album: x.album,
artist: x.artist,
}),
]),
])
}