storage.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * 公共存储库
  3. * @邠心vbe on 2021/04/20
  4. */
  5. import AsyncStorage from "@react-native-async-storage/async-storage"
  6. import app from '../../app.json';
  7. const DEBUG = app.debug && !app.product;
  8. /**
  9. * 通过key更新存储内容(内容必须为字符串或数字)
  10. * @param {*} key 要存储的字段名
  11. * @param {*} value 要存储的数据
  12. */
  13. export const setStorage = (key, value) => {
  14. AsyncStorage.setItem(key, value).then(res => {
  15. if (DEBUG) console.log('setStorage-' + key, res ? res : 'success');
  16. }).catch(err => {
  17. if (DEBUG) console.warn('setStorage-' + key, err);
  18. });
  19. }
  20. /**
  21. * 通过key更新存储内容(内容必须为json对象)
  22. * @param {*} key 要存储的字段名
  23. * @param {*} json 要存储的json数据
  24. */
  25. export const setStorageJson = (key, json) => {
  26. AsyncStorage.setItem(key, JSON.stringify(json)).then(res => {
  27. if (DEBUG) console.log('setStorageJson-' + key, res ? res : 'success');
  28. }).catch(err => {
  29. if (DEBUG) console.warn('setStorageJson-' + key, err);
  30. });
  31. }
  32. /**
  33. * 通过key获取存储内容
  34. * @param {*} key 存储的字段名
  35. * @returns 返回Promise用来获取数据
  36. */
  37. export const getStorage = (key) => {
  38. return AsyncStorage.getItem(key);
  39. }
  40. /**
  41. * 通过key获取存储内容
  42. * (同步方法,需使用async和await调用)
  43. * @param {*} key 存储的字段名
  44. * @returns 存储的数据(内容为字符串或数字)
  45. */
  46. export const getStorageSync = async (key) => {
  47. const result = await AsyncStorage.getItem(key);
  48. return result;
  49. }
  50. /**
  51. * 通过key获取存储的json数据
  52. * (同步方法,需使用async和await调用)
  53. * @param {*} key 存储的字段名
  54. * @returns 存储的数据(自动转化为json对象)
  55. */
  56. export const getStorageJsonSync = async (key) => {
  57. const result = await AsyncStorage.getItem(key);
  58. return result ? JSON.parse(result) : null;
  59. }
  60. export default storage = {
  61. getStorage: getStorage,
  62. getStorageSync: getStorageSync,
  63. getStorageJsonSync: getStorageJsonSync,
  64. setStorage: setStorage,
  65. setStorageJson: setStorageJson
  66. }