|
| 1 | +interface CachedRequestOptions { |
| 2 | + /** 过期时间,如果为 0 则表示永不过期 */ |
| 3 | + cacheTime?: number |
| 4 | + shouldCacheError?: boolean |
| 5 | +} |
| 6 | +interface CacheEntry<R> { |
| 7 | + data?: R |
| 8 | + time?: number |
| 9 | + error?: any |
| 10 | + requestPromise?: Promise<R> |
| 11 | +} |
| 12 | + |
| 13 | +type RequestFunctionWithCacheOptions<TContext = any> = ( |
| 14 | + details: Tampermonkey.Request<TContext> & CachedRequestOptions, |
| 15 | +) => Promise<Tampermonkey.Response<TContext>> |
| 16 | + |
| 17 | +export function createCachedRequest(requestFunction: RequestFunctionWithCacheOptions) { |
| 18 | + const cache = new Map<string, CacheEntry<any>>() |
| 19 | + |
| 20 | + return function cachedRequest<TContext extends any>( |
| 21 | + options: Tampermonkey.Request<TContext> & CachedRequestOptions, |
| 22 | + ): Promise<Tampermonkey.Response<TContext>> { |
| 23 | + if ( |
| 24 | + options.cacheTime !== undefined && |
| 25 | + (typeof options.cacheTime !== 'number' || options.cacheTime < 0) |
| 26 | + ) { |
| 27 | + throw new Error('无效的 cacheTime 选项') |
| 28 | + } |
| 29 | + |
| 30 | + const cacheKey = JSON.stringify(options) |
| 31 | + const cachedData = cache.get(cacheKey) |
| 32 | + |
| 33 | + if (cachedData) { |
| 34 | + const { data, time, error, requestPromise } = cachedData |
| 35 | + |
| 36 | + if (requestPromise) { |
| 37 | + return requestPromise |
| 38 | + } |
| 39 | + |
| 40 | + const cacheTime = options.cacheTime ?? 0 |
| 41 | + |
| 42 | + if (!error && time && cacheTime && Date.now() - time < cacheTime) { |
| 43 | + return Promise.resolve(data as Tampermonkey.Response<TContext>) |
| 44 | + } else { |
| 45 | + cache.delete(cacheKey) |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + const shouldCacheError = options.shouldCacheError ?? false |
| 50 | + |
| 51 | + const requestPromise = requestFunction(options) |
| 52 | + .then((data) => { |
| 53 | + const time = Date.now() |
| 54 | + cache.set(cacheKey, { data, time }) |
| 55 | + return data |
| 56 | + }) |
| 57 | + .catch((error) => { |
| 58 | + if (shouldCacheError) { |
| 59 | + const time = Date.now() |
| 60 | + cache.set(cacheKey, { error, time }) |
| 61 | + } |
| 62 | + throw error |
| 63 | + }) |
| 64 | + |
| 65 | + cache.set(cacheKey, { requestPromise }) |
| 66 | + |
| 67 | + return requestPromise |
| 68 | + } |
| 69 | +} |
0 commit comments