storage.ts 6.5 KB
Newer Older
1
import { isString } from '@vue/shared'
Q
qiang 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
import {
  defineSyncApi,
  defineAsyncApi,
  API_SET_STORAGE_SYNC,
  API_TYPE_SET_STORAGE_SYNC,
  API_SET_STORAGE,
  API_TYPE_SET_STORAGE,
  SetStorageProtocol,
  SetStorageSyncProtocol,
  API_GET_STORAGE_SYNC,
  GetStorageSyncProtocol,
  API_TYPE_GET_STORAGE_SYNC,
  API_GET_STORAGE,
  GetStorageProtocol,
  API_TYPE_GET_STORAGE,
  API_TYPE_REMOVE_STORAGE_SYNC,
  API_REMOVE_STORAGE,
  API_TYPE_REMOVE_STORAGE,
  RemoveStorageSyncProtocol,
  RemoveStorageProtocol,
} from '@dcloudio/uni-api'

import { warpPlusErrorCallback } from '../../../helpers/plus'

const STORAGE_DATA_TYPE = '__TYPE'
const STORAGE_KEYS = 'uni-storage-keys'

function parseValue(value: any) {
  const types = ['object', 'string', 'number', 'boolean', 'undefined']
  try {
32
    const object = isString(value) ? JSON.parse(value) : value
Q
qiang 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    const type = object.type
    if (types.indexOf(type) >= 0) {
      const keys = Object.keys(object)
      if (keys.length === 2 && 'data' in object) {
        // eslint-disable-next-line valid-typeof
        if (typeof object.data === type) {
          return object.data
        }
        // eslint-disable-next-line no-useless-escape
        if (
          type === 'object' &&
          /^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}Z$/.test(object.data)
        ) {
          // ISO 8601 格式返回 Date
          return new Date(object.data)
        }
      } else if (keys.length === 1) {
        return ''
      }
    }
  } catch (error) {}
}

export const setStorageSync = <API_TYPE_SET_STORAGE_SYNC>defineSyncApi(
  API_SET_STORAGE_SYNC,
  (key, data) => {
    const type = typeof data
    const value =
      type === 'string'
        ? data
        : JSON.stringify({
            type,
            data: data,
          })
    try {
      if (type === 'string' && parseValue(value) !== undefined) {
        plus.storage.setItem(key + STORAGE_DATA_TYPE, type)
      } else {
        plus.storage.removeItem(key + STORAGE_DATA_TYPE)
      }
      plus.storage.setItem(key, value)
    } catch (error) {}
  },
  SetStorageSyncProtocol
)

export const setStorage = <API_TYPE_SET_STORAGE>defineAsyncApi(
  API_SET_STORAGE,
  ({ key, data }, { resolve, reject }) => {
    const type = typeof data
    const value =
      type === 'string'
        ? data
        : JSON.stringify({
            type,
            data: data,
          })
    try {
      const storage = plus.storage
      if (type === 'string' && parseValue(value) !== undefined) {
        storage.setItemAsync(key + STORAGE_DATA_TYPE, type)
      } else {
        storage.removeItemAsync(key + STORAGE_DATA_TYPE)
      }
      storage.setItemAsync(key, value, resolve, warpPlusErrorCallback(reject))
98
    } catch (error: any) {
Q
qiang 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
      reject(error.message)
    }
  },
  SetStorageProtocol
)

function parseGetStorage(type: string, value: string) {
  let data: any = value
  if (
    type !== 'string' ||
    (type === 'string' && value === '{"type":"undefined"}')
  ) {
    try {
      // 兼容H5和V3初期历史格式
      let object = JSON.parse(value)
      const result = parseValue(object)
      if (result !== undefined) {
        data = result
      } else if (type) {
        // 兼容App端历史格式
        data = object
120
        if (isString(object)) {
Q
qiang 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
          object = JSON.parse(object)
          const objectType = typeof object
          if (objectType === 'number' && type === 'date') {
            data = new Date(object)
          } else if (
            objectType ===
            (['null', 'array'].indexOf(type) < 0 ? type : 'object')
          ) {
            data = object
          }
        }
      }
    } catch (error) {}
  }
  return data
}

export const getStorageSync = <API_TYPE_GET_STORAGE_SYNC>defineSyncApi(
  API_GET_STORAGE_SYNC,
  (key: string, t: boolean) => {
    const value = plus.storage.getItem(key)
    const typeOrigin = plus.storage.getItem(key + STORAGE_DATA_TYPE) || ''
    const type = typeOrigin.toLowerCase()
144
    if (!isString(value)) {
Q
qiang 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
      return ''
    }
    return parseGetStorage(type, value)
  },
  GetStorageSyncProtocol
)

export const getStorage = <API_TYPE_GET_STORAGE>defineAsyncApi(
  API_GET_STORAGE,
  ({ key }, { resolve, reject }) => {
    const storage = plus.storage
    storage.getItemAsync(
      key,
      function (res) {
        storage.getItemAsync(
          key + STORAGE_DATA_TYPE,
          function (typeRes) {
            const typeOrigin = typeRes.data || ''
            const type = typeOrigin.toLowerCase()
            resolve({
              data: parseGetStorage(type, res.data),
            })
          },
          function () {
            const type = ''
            resolve({
              data: parseGetStorage(type, res.data),
            })
          }
        )
      },
      warpPlusErrorCallback(reject)
    )
  },
  GetStorageProtocol
)

export const removeStorageSync = <API_TYPE_REMOVE_STORAGE_SYNC>defineSyncApi(
  API_REMOVE_STORAGE,
  (key) => {
    plus.storage.removeItem(key + STORAGE_DATA_TYPE)
    plus.storage.removeItem(key)
  },
  RemoveStorageSyncProtocol
)

export const removeStorage = <API_TYPE_REMOVE_STORAGE>defineAsyncApi(
  API_REMOVE_STORAGE,
  ({ key }, { resolve, reject }) => {
    // 兼容App端历史格式
    plus.storage.removeItemAsync(key + STORAGE_DATA_TYPE)
    plus.storage.removeItemAsync(key, resolve, warpPlusErrorCallback(reject))
  },
  RemoveStorageProtocol
)

export const clearStorageSync = <typeof uni.clearStorageSync>(
  defineSyncApi('clearStorageSync', () => {
    plus.storage.clear()
  })
)

export const clearStorage = <typeof uni.clearStorage>(
  defineAsyncApi('clearStorage', (_, { resolve, reject }) => {
    plus.storage.clearAsync(resolve, warpPlusErrorCallback(reject))
  })
)

export const getStorageInfoSync = <typeof uni.getStorageInfoSync>(
  defineSyncApi('getStorageInfoSync', () => {
    const length = plus.storage.getLength() || 0
    const keys: string[] = []
    let currentSize = 0
    for (let index = 0; index < length; index++) {
      const key = plus.storage.key(index)
      if (
        key !== STORAGE_KEYS &&
        (key.indexOf(STORAGE_DATA_TYPE) < 0 ||
          key.indexOf(STORAGE_DATA_TYPE) + STORAGE_DATA_TYPE.length !==
            key.length)
      ) {
        const value = plus.storage.getItem(key)
        currentSize += key.length + value.length
        keys.push(key)
      }
    }
    return {
      keys,
      currentSize: Math.ceil((currentSize * 2) / 1024),
      limitSize: Number.MAX_VALUE,
    }
  })
)

export const getStorageInfo = <typeof uni.getStorageInfo>(
  defineAsyncApi('getStorageInfo', (_, { resolve }) => {
    resolve(getStorageInfoSync())
  })
)