mirror of
https://github.com/dataease/dataease.git
synced 2026-06-13 01:01:20 +08:00
perf: 前端用户信息增加前缀避免 localStorage-key 冲突
This commit is contained in:
committed by
fit2cloud-chenyw
parent
c94355f8da
commit
ff1d3366be
@@ -1,17 +1,54 @@
|
||||
/**
|
||||
* 配置浏览器本地存储的方式,可直接存储对象数组。
|
||||
*/
|
||||
|
||||
// utils/cache.ts
|
||||
import WebStorageCache from 'web-storage-cache'
|
||||
|
||||
type CacheType = 'sessionStorage' | 'localStorage'
|
||||
type CacheType = 'localStorage' | 'sessionStorage'
|
||||
|
||||
const getPathPrefix = () => {
|
||||
const pathname = window.location.pathname
|
||||
const match = pathname.match(/^\/([^\/]+)/)
|
||||
return match ? `${match[1]}_` : 'de_v2_'
|
||||
}
|
||||
|
||||
export const useCache = (type: CacheType = 'localStorage') => {
|
||||
const wsCache: WebStorageCache = new WebStorageCache({
|
||||
storage: type
|
||||
const originalCache = new WebStorageCache({ storage: type })
|
||||
const prefix = getPathPrefix()
|
||||
|
||||
const shouldAddPrefix = (key: string): boolean => {
|
||||
return key.startsWith('user.')
|
||||
}
|
||||
|
||||
const processKey = (key: string): string => {
|
||||
return shouldAddPrefix(key) ? `${prefix}${key}` : key
|
||||
}
|
||||
|
||||
const methodsNeedKeyPrefix = new Set(['get', 'delete', 'touch', 'add', 'replace'])
|
||||
|
||||
const wrappedCache = new Proxy(originalCache, {
|
||||
get(target, prop, receiver) {
|
||||
const originalMethod = target[prop as keyof typeof target]
|
||||
|
||||
if (typeof originalMethod !== 'function') {
|
||||
return originalMethod
|
||||
}
|
||||
|
||||
if (methodsNeedKeyPrefix.has(prop as string)) {
|
||||
return function (this: any, key: string, ...args: any[]) {
|
||||
const processedKey = processKey(key)
|
||||
return originalMethod.call(target, processedKey, ...args)
|
||||
}
|
||||
}
|
||||
|
||||
if (prop === 'set') {
|
||||
return function (this: any, key: string, value: any, ...args: any[]) {
|
||||
const processedKey = processKey(key)
|
||||
return originalMethod.call(target, processedKey, value, ...args)
|
||||
}
|
||||
}
|
||||
return originalMethod.bind(target)
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
wsCache
|
||||
wsCache: wrappedCache
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { useCache } from '@/hooks/web/useCache'
|
||||
const { wsCache } = useCache()
|
||||
export const clearCache = () => {
|
||||
const keys = [
|
||||
'DataEaseKey',
|
||||
@@ -16,6 +18,6 @@ export const clearCache = () => {
|
||||
'user.uid'
|
||||
]
|
||||
keys.forEach(key => {
|
||||
localStorage.removeItem(key)
|
||||
wsCache.delete(key)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user