提交 2b3cb78c 作者: 方治民

feat: 统一实现 Storage 和相关使用方法

上级 5f3c8f13
import { convertKB } from '@/utils/file'
import { Storage } from '@/utils/storage'
/**
* 图片 Hash 缓存标识前缀
......@@ -10,12 +11,11 @@ export const CACHE_PREFIX = 'G_CACHE_IMAGE__'
* @returns 字节
*/
export function calculateCacheSize() {
const storage = uni.getStorageInfoSync()
return storage.keys
return Storage.keys()
.filter((key) => key.startsWith(CACHE_PREFIX))
.reduce((total, key) => {
try {
const cache = uni.getStorageSync(key)
const cache = Storage.get(key)
const result = JSON.parse(cache)
total += result.size
} catch (_) {}
......@@ -42,13 +42,12 @@ export function calculateCacheSizeFormat() {
* 清理缓存
*/
export function cleanCache() {
const storage = uni.getStorageInfoSync()
const promises = storage.keys
const promises = Storage.keys()
.filter((key) => key.startsWith(CACHE_PREFIX))
.map((key) => {
return new Promise((resolve, reject) => {
try {
const cache = uni.getStorageSync(key)
const cache = Storage.get(key)
const result = JSON.parse(cache)
uni.removeSavedFile({
filePath: result.url,
......@@ -58,7 +57,7 @@ export function cleanCache() {
console.error(e)
reject(e)
} finally {
uni.removeStorageSync(key)
Storage.remove(key)
}
})
})
......
<script setup lang="ts">
import md5 from 'crypto-js/md5'
import { CACHE_PREFIX } from './index'
import { Storage } from '@/utils/storage'
const props = defineProps({
width: {
......@@ -63,7 +64,7 @@
// #ifdef APP-PLUS
const hash = md5(url).toString().toUpperCase()
hashCacheKey.value = `${CACHE_PREFIX}${hash}`
const cache = uni.getStorageSync(hashCacheKey.value)
const cache = Storage.get(hashCacheKey.value)
if (cache) {
log('cache hit', url)
try {
......@@ -100,7 +101,7 @@
url = `${savedFilePath}`
// 缓存图片本地地址
uni.setStorageSync(
Storage.set(
hashCacheKey.value,
JSON.stringify({
url,
......@@ -133,7 +134,7 @@
hasError.value = true
visibleSrc.value = props.src
// 清除缓存
hashCacheKey.value && uni.removeStorageSync(hashCacheKey.value)
hashCacheKey.value && Storage.remove(hashCacheKey.value)
console.warn('CacheImage cache error')
}
</script>
......
import { APP_UUID_KEY } from '/@/enums/cacheEnum'
import { nanoid } from 'nanoid'
import md5 from 'crypto-js/md5'
import { Storage } from '@/utils/storage'
interface DeviceInfo {
uuid: string
......@@ -43,7 +44,7 @@ export function useRuntime(): Runtime {
let uuid = uni.getStorageSync(APP_UUID_KEY)
if (!uuid) {
uuid = md5(nanoid()).toString()
uni.setStorageSync(APP_UUID_KEY, uuid)
Storage.set(APP_UUID_KEY, uuid)
}
const result = { uuid, vendor: 'unknown', model: 'unknown' }
const userAgent = navigator.userAgent
......
import { defineStore } from 'pinia'
import { store } from '/@/store'
import { getAuthCache, setAuthCache } from '@/utils/auth'
import { Storage } from '@/utils/storage'
import { TOKEN_KEY, USER_INFO_KEY } from '@/enums/cacheEnum'
import type { defs } from '@/api/services'
import Navigate from '@/utils/page/navigate'
......@@ -26,7 +26,7 @@ export const useUserStore = defineStore({
return this.token
}
const token = getAuthCache(TOKEN_KEY)
const token = Storage.get(TOKEN_KEY)
if (token) {
this.token = token
return token
......@@ -37,7 +37,7 @@ export const useUserStore = defineStore({
return this.userInfo
}
const info = getAuthCache(USER_INFO_KEY)
const info = Storage.get(USER_INFO_KEY)
if (info) {
const userInfo = JSON.parse(info) as UserInfo
this.userInfo = userInfo
......@@ -56,11 +56,11 @@ export const useUserStore = defineStore({
actions: {
setToken(token: string) {
this.token = token
setAuthCache(TOKEN_KEY, token)
Storage.set(TOKEN_KEY, token)
},
setUserInfo(info: UserInfo) {
this.userInfo = info
setAuthCache(USER_INFO_KEY, info ? JSON.stringify(info) : null)
Storage.set(USER_INFO_KEY, info ? JSON.stringify(info) : null)
},
async logout() {
if (this.loading) {
......
import { TOKEN_KEY } from '/@/enums/cacheEnum'
export function getToken() {
return getAuthCache(TOKEN_KEY)
}
export function getAuthCache(key: string): string | null {
let value: string | null = null
// #ifdef APP-PLUS
value = plus.storage.getItem(key)
// #endif
// #ifndef APP-PLUS
try {
value = uni.getStorageSync(key)
if (value) {
return value
}
} catch (e) {}
// #endif
return value
}
export function setAuthCache(key: string, value: string) {
// #ifdef APP-PLUS
plus.storage.setItem(key, value)
// #endif
// #ifndef APP-PLUS
try {
uni.setStorageSync(key, value)
} catch (e) {}
// #endif
}
export function clearAuthCache() {
// #ifdef APP-PLUS
plus.storage.clear()
// #endif
// #ifndef APP-PLUS
try {
uni.clearStorageSync()
} catch (e) {}
// #endif
}
......@@ -12,14 +12,13 @@ import { useI18n } from '/@/hooks/app/useI18n'
import { useMessage } from '/@/hooks/app/useMessage'
import { ContentTypeEnum, RequestEnum } from '/@/enums/httpEnum'
import { isString } from '/@/utils/is'
import { getToken, setAuthCache } from '/@/utils/auth'
import { deepMerge, setObjToUrlParams } from '/@/utils'
import { formatRequestDate, joinTimestamp } from './helper'
import { AxiosRetry } from '/@/utils/http/axios/axiosRetry'
import * as HTTP from '/@/api/types'
import { API_URL, API_URL_PREFIX } from '/@/utils/net'
import { handleResponseResource } from '/@/utils/proxy'
import { TOKEN_KEY } from '@/enums/cacheEnum'
import { useUserStoreWithOut } from '@/store/modules/user'
const globSetting = useGlobSetting()
const urlPrefix = globSetting.urlPrefix
......@@ -68,7 +67,8 @@ const transform: AxiosTransform = {
timeoutMsg = t('sys.api.timeoutMessage')
// 清空 token
setAuthCache(TOKEN_KEY, '')
const userStore = useUserStoreWithOut()
userStore.setToken('')
// 判断当前页面是否为登录页,防止多个请求时重复跳转
const page = getCurrentPages()[0]
......@@ -153,7 +153,8 @@ const transform: AxiosTransform = {
*/
requestInterceptors: (config, options) => {
// 请求之前处理config
const token = getToken()
const userStore = useUserStoreWithOut()
const token = userStore.getToken
if (token && (config as Recordable)?.requestOptions?.withToken !== false) {
// jwt token
;(config as Recordable).headers.Authorization = options.authenticationScheme
......
import type { Client, Frame, Message } from 'stompjs'
import Stomp from './uni-stomp'
import UniWebSocket from './uni-websocket'
import { getToken } from '/@/utils/auth'
import { useMessage } from '/@/hooks/app/useMessage'
import { API_URL, API_URL_PREFIX } from '/@/utils/net'
import { useUserStoreWithOut } from '@/store/modules/user'
const { createMessage } = useMessage()
......@@ -83,7 +83,8 @@ class StompInstance {
}
// 从缓存中获取token
const token = getToken()
const useStore = useUserStoreWithOut()
const token = useStore.getToken
const options = token ? { token } : {}
// TODO: 检查 Token 是否有效
......
function catchError(e: any) {
console.error(e)
}
function get(key: string) {
let value: string | null = null
try {
// #ifdef APP-PLUS
value = plus.storage.getItem(key)
// #endif
// #ifndef APP-PLUS
value = uni.getStorageSync(key)
// #endif
} catch (e) {
catchError(e)
}
return value
}
function set(key: string, value: string) {
try {
// #ifdef APP-PLUS
plus.storage.setItem(key, value)
// #endif
// #ifndef APP-PLUS
uni.setStorageSync(key, value)
// #endif
} catch (e) {
catchError(e)
}
}
function remove(key: string) {
try {
// #ifdef APP-PLUS
plus.storage.removeItem(key)
// #endif
// #ifndef APP-PLUS
uni.removeStorageSync(key)
// #endif
} catch (e) {
catchError(e)
}
}
function clear() {
try {
// #ifdef APP-PLUS
plus.storage.clear()
// #endif
// #ifndef APP-PLUS
uni.clearStorageSync()
// #endif
} catch (e) {
catchError(e)
}
}
function keys() {
let keys = []
try {
// #ifdef APP-PLUS
keys = plus.storage.getAllKeys()
// #endif
// #ifndef APP-PLUS
keys = uni.getStorageInfoSync().keys
// #endif
} catch (e) {
catchError(e)
}
return keys
}
/**
* 兼容 uni-app 和 plus 的持久化 Storage
*/
export const Storage = {
get,
set,
remove,
clear,
keys,
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论