|
1 | 1 | import WebStorageCache from 'web-storage-cache' |
2 | 2 |
|
3 | | -type CacheType = 'sessionStorage' | 'localStorage' |
| 3 | +type CacheType = 'localStorage' | 'sessionStorage' |
| 4 | + |
| 5 | +const getPathPrefix = () => { |
| 6 | + const pathname = window.location.pathname |
| 7 | + // eslint-disable-next-line no-useless-escape |
| 8 | + const match = pathname.match(/^\/([^\/]+)/) |
| 9 | + return match ? `${match[1]}_` : 'sqlbot_v1_' |
| 10 | +} |
4 | 11 |
|
5 | 12 | export const useCache = (type: CacheType = 'localStorage') => { |
6 | | - const wsCache: WebStorageCache = new WebStorageCache({ |
7 | | - storage: type, |
| 13 | + const originalCache = new WebStorageCache({ storage: type }) |
| 14 | + const prefix = getPathPrefix() |
| 15 | + |
| 16 | + const methodsNeedKeyPrefix = new Set(['get', 'delete', 'touch', 'add', 'replace']) |
| 17 | + |
| 18 | + const wrappedCache = new Proxy(originalCache, { |
| 19 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 20 | + get(target, prop, _receiver) { |
| 21 | + const originalMethod = target[prop as keyof typeof target] |
| 22 | + |
| 23 | + if (typeof originalMethod !== 'function') { |
| 24 | + return originalMethod |
| 25 | + } |
| 26 | + |
| 27 | + if (methodsNeedKeyPrefix.has(prop as string)) { |
| 28 | + return function (this: any, key: string, ...args: any[]) { |
| 29 | + // 自动加上前缀 |
| 30 | + const scopedKey = `${prefix}${key}` |
| 31 | + return (originalMethod as (...args: any[]) => any).apply(target, [scopedKey, ...args]) |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + if (prop === 'set') { |
| 36 | + return function (this: any, key: string, value: any, ...args: any[]) { |
| 37 | + const scopedKey = `${prefix}${key}` |
| 38 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type |
| 39 | + return (originalMethod as Function).apply(target, [scopedKey, value, ...args]) |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return originalMethod.bind(target) |
| 44 | + }, |
8 | 45 | }) |
9 | 46 |
|
10 | 47 | return { |
11 | | - wsCache, |
| 48 | + wsCache: wrappedCache, |
12 | 49 | } |
13 | 50 | } |
0 commit comments