(type: CacheType = 'localStorage')
| 10 | } |
| 11 | |
| 12 | export const useCache = (type: CacheType = 'localStorage') => { |
| 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 | }, |
| 45 | }) |
| 46 | |
| 47 | return { |
| 48 | wsCache: wrappedCache, |
| 49 | } |
| 50 | } |
no test coverage detected