wudebin 6 місяців тому
батько
коміт
6fe681f172
1 змінених файлів з 73 додано та 0 видалено
  1. 73 0
      Strides-SPAPP/app/utils/storage.js

+ 73 - 0
Strides-SPAPP/app/utils/storage.js

@@ -0,0 +1,73 @@
+/**
+ * 公共存储库
+ * @邠心vbe on 2021/04/20
+ */
+import AsyncStorage from "@react-native-async-storage/async-storage"
+import app from '../../app.json';
+
+const DEBUG = app.debug && !app.product;
+
+/**
+ * 通过key更新存储内容(内容必须为字符串或数字)
+ * @param {*} key 要存储的字段名
+ * @param {*} value 要存储的数据
+ */
+export const setStorage = (key, value) => {
+  AsyncStorage.setItem(key, value).then(res => {
+    if (DEBUG) console.log('setStorage-' + key, res ? res : 'success');
+  }).catch(err => {
+    if (DEBUG) console.warn('setStorage-' + key, err);
+  });
+}
+
+/**
+ * 通过key更新存储内容(内容必须为json对象)
+ * @param {*} key 要存储的字段名
+ * @param {*} json 要存储的json数据
+ */
+export const setStorageJson = (key, json) => {
+  AsyncStorage.setItem(key, JSON.stringify(json)).then(res => {
+    if (DEBUG) console.log('setStorageJson-' + key, res ? res : 'success');
+  }).catch(err => {
+    if (DEBUG) console.warn('setStorageJson-' + key, err);
+  });
+}
+
+/**
+ * 通过key获取存储内容
+ * @param {*} key 存储的字段名
+ * @returns 返回Promise用来获取数据
+ */
+export const getStorage = (key) => {
+  return AsyncStorage.getItem(key);
+}
+
+/**
+ * 通过key获取存储内容
+ * (同步方法,需使用async和await调用)
+ * @param {*} key 存储的字段名
+ * @returns 存储的数据(内容为字符串或数字)
+ */
+export const getStorageSync = async (key) => {
+  const result = await AsyncStorage.getItem(key);
+  return result;
+}
+
+/**
+ * 通过key获取存储的json数据
+ * (同步方法,需使用async和await调用)
+ * @param {*} key 存储的字段名
+ * @returns 存储的数据(自动转化为json对象)
+ */
+export const getStorageJsonSync = async (key) => {
+  const result = await AsyncStorage.getItem(key);
+  return result ? JSON.parse(result) : null;
+}
+
+export default storage = {
+  getStorage: getStorage,
+  getStorageSync: getStorageSync,
+  getStorageJsonSync: getStorageJsonSync,
+  setStorage: setStorage,
+  setStorageJson: setStorageJson
+}