| 7 | * 构建一个存储对象 |
| 8 | */ |
| 9 | export function buildStorage(backend: any) { |
| 10 | const storage = new Storage({ |
| 11 | // 最大容量,默认值1000条数据循环存储 |
| 12 | size: 1000, |
| 13 | |
| 14 | // 存储引擎:对于RN使用AsyncStorage,对于web使用window.localStorage |
| 15 | // 如果不指定则数据只会保存在内存中,重启后即丢失 |
| 16 | // storageBackend: |
| 17 | // config.platform === 'app' |
| 18 | // ? require('react-native').AsyncStorage |
| 19 | // : window.localStorage, |
| 20 | storageBackend: backend, |
| 21 | |
| 22 | // 数据过期时间,默认一整天(1000 * 3600 * 24 毫秒),设为null则永不过期 |
| 23 | defaultExpires: 1000 * 3600 * 24, |
| 24 | |
| 25 | // 读写时在内存中缓存数据。默认启用。 |
| 26 | enableCache: true, |
| 27 | |
| 28 | // 如果storage中没有相应数据,或数据已过期, |
| 29 | // 则会调用相应的sync方法,无缝返回最新数据。 |
| 30 | // sync方法的具体说明会在后文提到 |
| 31 | // 你可以在构造函数这里就写好sync的方法 |
| 32 | // 或是在任何时候,直接对storage.sync进行赋值修改 |
| 33 | // 或是写到另一个文件里,这里require引入 |
| 34 | // sync: require('你可以另外写一个文件专门处理sync') |
| 35 | }); |
| 36 | |
| 37 | const rnStorage = { |
| 38 | set: async (key: string, data: any) => { |
| 39 | try { |
| 40 | if (!!key && typeof key === 'string' && !_isUndefined(data)) { |
| 41 | await storage.save({ key, data }); |
| 42 | } |
| 43 | } catch (e) { |
| 44 | console.error(e); |
| 45 | } |
| 46 | |
| 47 | return data; |
| 48 | }, |
| 49 | /** |
| 50 | * 自定义过期时间的存储 |
| 51 | * set默认为1天,该方法自定义过期时间 |
| 52 | */ |
| 53 | setWithExpires: async (key: string, data: any, expires: number) => { |
| 54 | try { |
| 55 | if (!!key && typeof key === 'string' && !_isUndefined(data)) { |
| 56 | await storage.save({ key, data, expires }); |
| 57 | } |
| 58 | } catch (e) { |
| 59 | console.error(e); |
| 60 | } |
| 61 | |
| 62 | return data; |
| 63 | }, |
| 64 | get: async (key: string, defaultVal?: any) => { |
| 65 | let res: any; |
| 66 | try { |