xref: /MusicFree/src/utils/storage.ts (revision 242960d3fe7b3524027774192799cef72e2b818e)
1*242960d3S猫头猫import { errorLog } from '@/utils/log';
2*242960d3S猫头猫import AsyncStorage from '@react-native-async-storage/async-storage';
3*242960d3S猫头猫
4*242960d3S猫头猫export async function setStorage(key: string, value: any) {
5*242960d3S猫头猫  try {
6*242960d3S猫头猫    await AsyncStorage.setItem(key, JSON.stringify(value, null, ''));
7*242960d3S猫头猫  } catch(e: any) {
8*242960d3S猫头猫    errorLog('存储失败', e?.message)
9*242960d3S猫头猫  }
10*242960d3S猫头猫}
11*242960d3S猫头猫
12*242960d3S猫头猫export async function getStorage(key: string) {
13*242960d3S猫头猫  try {
14*242960d3S猫头猫    const result = await AsyncStorage.getItem(key);
15*242960d3S猫头猫    if (result) {
16*242960d3S猫头猫      return JSON.parse(result);
17*242960d3S猫头猫    }
18*242960d3S猫头猫  } catch {}
19*242960d3S猫头猫  return null;
20*242960d3S猫头猫}
21*242960d3S猫头猫
22*242960d3S猫头猫export async function getMultiStorage(keys: string[]) {
23*242960d3S猫头猫  if (keys.length === 0) {
24*242960d3S猫头猫    return [];
25*242960d3S猫头猫  }
26*242960d3S猫头猫  const result = await AsyncStorage.multiGet(keys);
27*242960d3S猫头猫
28*242960d3S猫头猫  return result.map(_ => {
29*242960d3S猫头猫    try {
30*242960d3S猫头猫      if (_[1]) {
31*242960d3S猫头猫        return JSON.parse(_[1]);
32*242960d3S猫头猫      }
33*242960d3S猫头猫      return null;
34*242960d3S猫头猫    } catch {
35*242960d3S猫头猫      return null;
36*242960d3S猫头猫    }
37*242960d3S猫头猫  });
38*242960d3S猫头猫}
39*242960d3S猫头猫
40*242960d3S猫头猫export async function removeStorage(key: string) {
41*242960d3S猫头猫  return AsyncStorage.removeItem(key);
42*242960d3S猫头猫}
43