提交 2b3cb78c 作者: 方治民

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

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