#!/bin/bash set -eu cd /workspace/repo git apply <<'REFERENCE_PATCH' diff --git a/packages/hooks/src/useRequest/__tests__/useCachePlugin.spec.tsx b/packages/hooks/src/useRequest/__tests__/useCachePlugin.spec.tsx index 2ab551c7..3f8f5814 100644 --- a/packages/hooks/src/useRequest/__tests__/useCachePlugin.spec.tsx +++ b/packages/hooks/src/useRequest/__tests__/useCachePlugin.spec.tsx @@ -183,6 +183,562 @@ describe('useCachePlugin', () => { expect(result.current.data).toBe('success'); }); + const pageRequest = (calls: string[]) => (page: string, delay: number) => { + calls.push(page); + return new Promise((resolve) => { + setTimeout(() => resolve(`data-${page}`), delay); + }); + }; + + test('superseded response should still reach a custom setCache', async () => { + const store: Record = {}; + const { result } = setup(pageRequest([]), { + manual: true, + cacheKey: 'supersededSetCache', + setCache: (data) => { + store[data.params[0]] = data; + }, + getCache: (params) => store[params[0]], + }); + + act(() => { + result.current.run('a', 300); + }); + act(() => { + result.current.run('b', 600); + }); + await act(async () => { + vi.advanceTimersByTime(400); + }); + expect(store.a?.data).toBe('data-a'); + expect(result.current.data).toBeUndefined(); + + await act(async () => { + vi.advanceTimersByTime(300); + }); + expect(store.b?.data).toBe('data-b'); + expect(result.current.data).toBe('data-b'); + }); + + test('late response should not replace newer data in the cache', async () => { + const request = pageRequest([]); + const hook1 = setup(request, { manual: true, cacheKey: 'lateResponse' }); + const hook2 = setup(request, { manual: true, cacheKey: 'lateResponse' }); + + act(() => { + hook1.result.current.run('a', 800); + }); + act(() => { + hook2.result.current.run('a', 800); + }); + act(() => { + hook1.result.current.run('b', 200); + }); + await act(async () => { + vi.advanceTimersByTime(900); + }); + + expect(hook1.result.current.data).toBe('data-b'); + expect(hook1.result.current.params).toEqual(['b', 200]); + expect(hook2.result.current.data).toBe('data-a'); + expect(setup(request, { manual: true, cacheKey: 'lateResponse' }).result.current.data).toBe( + 'data-b', + ); + }); + + test('requests with different params should not share an in-flight request', async () => { + const calls: string[] = []; + const request = pageRequest(calls); + const hook1 = setup(request, { manual: true, cacheKey: 'differentParams' }); + const hook2 = setup(request, { manual: true, cacheKey: 'differentParams' }); + + act(() => { + hook1.result.current.run('a', 500); + }); + act(() => { + hook2.result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(600); + }); + + expect(calls).toEqual(['a', 'b']); + expect(hook1.result.current.data).toBe('data-a'); + expect(hook2.result.current.data).toBe('data-b'); + }); + + test('settled request should not drop a newer in-flight request', async () => { + const calls: string[] = []; + const request = pageRequest(calls); + const hook1 = setup(request, { manual: true, cacheKey: 'newerInFlight' }); + + act(() => { + hook1.result.current.run('a', 50); + }); + act(() => { + hook1.result.current.run('b', 500); + }); + await act(async () => { + vi.advanceTimersByTime(100); + }); + + const hook2 = setup(request, { manual: true, cacheKey: 'newerInFlight' }); + act(() => { + hook2.result.current.run('b', 500); + }); + await act(async () => { + vi.advanceTimersByTime(500); + }); + + expect(calls).toEqual(['a', 'b']); + expect(hook2.result.current.data).toBe('data-b'); + }); + + test('responses arriving in reverse order should all reach a per-params store', async () => { + const store: Record = {}; + const { result } = setup(pageRequest([]), { + manual: true, + cacheKey: 'reverseOrderStore', + setCache: (data) => { + store[data.params[0]] = data; + }, + getCache: (params) => store[params[0]], + }); + + act(() => { + result.current.run('a', 900); + }); + act(() => { + result.current.run('b', 600); + }); + act(() => { + result.current.run('c', 300); + }); + await act(async () => { + vi.advanceTimersByTime(1000); + }); + + expect(Object.keys(store).sort()).toEqual(['a', 'b', 'c']); + expect(result.current.data).toBe('data-c'); + }); + + test('responses arriving in reverse order should leave a single-entry store on the newest', async () => { + let entry: any; + const { result } = setup(pageRequest([]), { + manual: true, + cacheKey: 'reverseOrderSingle', + setCache: (data) => { + entry = data; + }, + getCache: () => entry, + }); + + act(() => { + result.current.run('a', 900); + }); + act(() => { + result.current.run('b', 600); + }); + act(() => { + result.current.run('c', 300); + }); + await act(async () => { + vi.advanceTimersByTime(1000); + }); + + expect(entry?.data).toBe('data-c'); + }); + + test('a late page another instance still shows should reach a per-params store', async () => { + const store: Record = {}; + const request = pageRequest([]); + const options = { + manual: true, + cacheKey: 'lateShownPage', + setCache: (data: any) => { + store[data.params[0]] = data; + }, + getCache: (params: any[]) => store[params[0]], + }; + const hook1 = setup(request, options); + const hook2 = setup(request, options); + + act(() => { + hook1.result.current.run('a', 700); + }); + act(() => { + hook2.result.current.run('a', 700); + }); + act(() => { + hook1.result.current.run('b', 200); + }); + await act(async () => { + vi.advanceTimersByTime(800); + }); + + expect(hook2.result.current.data).toBe('data-a'); + expect(store.a?.data).toBe('data-a'); + expect(store.b?.data).toBe('data-b'); + }); + + test('mutate should reach instances with the same params only', async () => { + const request = pageRequest([]); + const options = { manual: true, cacheKey: 'mutateSameParams' }; + const hook1 = setup(request, options); + const hook2 = setup(request, options); + const hook3 = setup(request, options); + + act(() => { + hook1.result.current.run('a', 100); + }); + act(() => { + hook2.result.current.run('a', 100); + }); + await act(async () => { + vi.advanceTimersByTime(150); + }); + act(() => { + hook3.result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(150); + }); + act(() => { + hook1.result.current.mutate('data-a-edited'); + }); + + expect(hook2.result.current.data).toBe('data-a-edited'); + expect(hook3.result.current.data).toBe('data-b'); + }); + + test('superseded response arriving last should still reach a per-params store', async () => { + const store: Record = {}; + const { result } = setup(pageRequest([]), { + manual: true, + cacheKey: 'supersededLast', + setCache: (data) => { + store[data.params[0]] = data; + }, + getCache: (params) => store[params[0]], + }); + + act(() => { + result.current.run('a', 300); + }); + act(() => { + result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(400); + }); + + expect(result.current.data).toBe('data-b'); + expect(store.a?.data).toBe('data-a'); + }); + + test('a single-entry store should hold the params requested last across instances', async () => { + let entry: any; + const request = pageRequest([]); + const options = { + manual: true, + cacheKey: 'singleEntryInstances', + setCache: (data: any) => { + entry = data; + }, + getCache: () => entry, + }; + const hook1 = setup(request, options); + const hook2 = setup(request, options); + + act(() => { + hook1.result.current.run('a', 300); + }); + act(() => { + hook2.result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(400); + }); + + expect(hook1.result.current.data).toBe('data-a'); + expect(entry?.data).toBe('data-b'); + }); + + test('the built-in cache should hold the params requested last across instances', async () => { + const request = pageRequest([]); + const options = { manual: true, cacheKey: 'builtInInstances' }; + const hook1 = setup(request, options); + const hook2 = setup(request, options); + + act(() => { + hook1.result.current.run('a', 300); + }); + act(() => { + hook2.result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(400); + }); + + expect(hook1.result.current.data).toBe('data-a'); + expect(setup(request, options).result.current.data).toBe('data-b'); + }); + + test('an instance without params should follow the newest response', async () => { + const request = pageRequest([]); + const options = { manual: true, cacheKey: 'noParamsInstance' }; + const hook1 = setup(request, options); + const hook2 = setup(request, options); + + act(() => { + hook1.result.current.run('a', 500); + }); + act(() => { + hook2.result.current.run('a', 500); + }); + act(() => { + hook1.result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(50); + }); + const hook3 = setup(request, options); + await act(async () => { + vi.advanceTimersByTime(550); + }); + + expect(hook2.result.current.data).toBe('data-a'); + expect(hook3.result.current.data).toBe('data-b'); + }); + + test('an instance requesting other params should show its own response', async () => { + const request = pageRequest([]); + const options = { manual: true, cacheKey: 'otherParamsLater' }; + const hook1 = setup(request, options); + const hook2 = setup(request, options); + + act(() => { + hook1.result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(150); + }); + act(() => { + hook2.result.current.run('a', 100); + }); + await act(async () => { + vi.advanceTimersByTime(150); + }); + + expect(hook2.result.current.data).toBe('data-a'); + expect(hook1.result.current.data).toBe('data-b'); + }); + + test('an instance sharing a request should take a newer response for the same params', async () => { + const delays = [400, 100]; + let count = 0; + const request = (page: string) => { + count += 1; + const n = count; + return new Promise((resolve) => { + setTimeout(() => resolve(`data-${page}-${n}`), delays.shift()); + }); + }; + const options = { manual: true, cacheKey: 'sharedThenRefreshed' }; + const hook1 = setup(request, options); + const hook2 = setup(request, options); + + act(() => { + hook1.result.current.run('a'); + }); + act(() => { + hook2.result.current.run('a'); + }); + await act(async () => { + vi.advanceTimersByTime(50); + }); + act(() => { + hook1.result.current.refresh(); + }); + await act(async () => { + vi.advanceTimersByTime(500); + }); + + expect(hook1.result.current.data).toBe('data-a-2'); + expect(hook2.result.current.data).toBe('data-a-2'); + }); + + test('an instance mounted with the params in flight should share the request', async () => { + const calls: string[] = []; + const request = pageRequest(calls); + const hook1 = setup(request, { manual: true, cacheKey: 'mountedMidLoad' }); + + act(() => { + hook1.result.current.run('a', 100); + hook1.result.current.run('b', 1000); + }); + await act(async () => { + vi.advanceTimersByTime(151); + }); + const hook2 = setup(request, { cacheKey: 'mountedMidLoad', defaultParams: ['b', 1000] }); + await act(async () => { + vi.advanceTimersByTime(1000); + }); + + expect(calls).toEqual(['a', 'b']); + expect(hook2.result.current.data).toBe('data-b'); + }); + + test('the built-in cache should keep every page loaded under a key', async () => { + const request = pageRequest([]); + const options = { manual: true, cacheKey: 'keepEveryPage' }; + const hook1 = setup(request, options); + + act(() => { + hook1.result.current.run('a', 100); + }); + await act(async () => { + vi.advanceTimersByTime(100); + }); + act(() => { + hook1.result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(100); + }); + + const hook2 = setup(request, options); + expect(hook2.result.current.data).toBe('data-b'); + act(() => { + hook2.result.current.run('a', 100); + }); + expect(hook2.result.current.data).toBe('data-a'); + }); + + test('a fresh page should be served again without a request', async () => { + const calls: string[] = []; + const request = pageRequest(calls); + const { result } = setup(request, { + manual: true, + cacheKey: 'freshPageAgain', + staleTime: 10000, + }); + + act(() => { + result.current.run('a', 100); + }); + await act(async () => { + vi.advanceTimersByTime(100); + }); + act(() => { + result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(100); + }); + act(() => { + result.current.run('a', 100); + }); + + expect(result.current.data).toBe('data-a'); + expect(result.current.loading).toBe(false); + expect(calls).toEqual(['a', 'b']); + }); + + test('a superseded response should be kept in the built-in cache for its own params', async () => { + const request = pageRequest([]); + const options = { manual: true, cacheKey: 'supersededBuiltIn' }; + const hook1 = setup(request, options); + + act(() => { + hook1.result.current.run('a', 300); + }); + act(() => { + hook1.result.current.run('b', 100); + }); + await act(async () => { + vi.advanceTimersByTime(400); + }); + + const hook2 = setup(request, options); + expect(hook2.result.current.data).toBe('data-b'); + act(() => { + hook2.result.current.run('a', 300); + }); + expect(hook2.result.current.data).toBe('data-a'); + }); + + test('a superseded response should be cached under the cacheKey it was requested with', async () => { + const request = pageRequest([]); + const hook = renderHook( + ({ page }) => + useRequest(() => request(page, page === 'a' ? 300 : 100), { + cacheKey: `keyPerPage-${page}`, + refreshDeps: [page], + }), + { initialProps: { page: 'a' } }, + ); + await act(async () => { + vi.advanceTimersByTime(50); + }); + hook.rerender({ page: 'b' }); + await act(async () => { + vi.advanceTimersByTime(400); + }); + expect(hook.result.current.data).toBe('data-b'); + + hook.rerender({ page: 'a' }); + expect(hook.result.current.data).toBe('data-a'); + }); + + test('an instance should follow its current cacheKey, not the one it mounted with', async () => { + const request = pageRequest([]); + const useList = ({ page }: { page: string }) => + useRequest(() => request(page, page === 'a' ? 300 : 500), { + cacheKey: `followKey-${page}`, + refreshDeps: [page], + }); + const hook1 = renderHook(useList, { initialProps: { page: 'a' } }); + const hook2 = renderHook(useList, { initialProps: { page: 'a' } }); + + await act(async () => { + vi.advanceTimersByTime(50); + }); + hook2.rerender({ page: 'b' }); + await act(async () => { + vi.advanceTimersByTime(300); + }); + + expect(hook1.result.current.data).toBe('data-a'); + expect(hook2.result.current.data).toBeUndefined(); + }); + + test('cached data of other params should not be returned as fresh', async () => { + const calls: string[] = []; + const request = pageRequest(calls); + const options = { manual: true, cacheKey: 'otherParamsFresh', staleTime: 10000 }; + const hook1 = setup(request, options); + + act(() => { + hook1.result.current.run('a', 100); + }); + await act(async () => { + vi.advanceTimersByTime(100); + }); + + act(() => { + hook1.result.current.run('b', 100); + }); + expect(calls).toEqual(['a', 'b']); + expect(hook1.result.current.loading).toBe(true); + await act(async () => { + vi.advanceTimersByTime(100); + }); + + expect(calls).toEqual(['a', 'b']); + expect(hook1.result.current.data).toBe('data-b'); + }); + //github.com/alibaba/hooks/issues/1859 test('error should reset with activeKey', async () => { const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); diff --git a/packages/hooks/src/useRequest/src/Fetch.ts b/packages/hooks/src/useRequest/src/Fetch.ts index 2039b2c9..3b44e1ff 100644 --- a/packages/hooks/src/useRequest/src/Fetch.ts +++ b/packages/hooks/src/useRequest/src/Fetch.ts @@ -82,6 +82,7 @@ export default class Fetch { const res = await servicePromise; if (currentCount !== this.count) { + this.runPluginHandler('onSuperseded', res, params); throw new CancelledError(); } diff --git a/packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts b/packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts index ba6aa886..891ea026 100644 --- a/packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts +++ b/packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts @@ -1,12 +1,41 @@ import { useRef } from 'react'; import useCreation from '../../../useCreation'; import useUnmount from '../../../useUnmount'; +import { depsEqual } from '../../../utils/depsEqual'; import type { Plugin } from '../types'; import { setCache, getCache } from '../utils/cache'; import type { CachedData } from '../utils/cache'; import { setCachePromise, getCachePromise } from '../utils/cachePromise'; import { trigger, subscribe } from '../utils/cacheSubscribe'; +// Start order of requests across all instances. A write is dropped when a request +// that started later has already written the same cacheKey. +let requestOrder = 0; +const orderOfPromise = new WeakMap, number>(); +const orderOfParams = new WeakMap(); +const lastWrittenOrder = new Map(); +// Start order of the request behind each entry written, per cacheKey and params. +const writtenOrders = new Map(); + +const orderWrittenFor = (key: string, params: any[]) => + writtenOrders.get(key)?.find((entry) => depsEqual(entry.params, params))?.order; + +const recordWritten = (key: string, params: any[], order: number) => { + const entries = writtenOrders.get(key) ?? []; + const entry = entries.find((e) => depsEqual(e.params, params)); + if (entry) { + entry.order = Math.max(entry.order, order); + } else { + entries.push({ params, order }); + } + writtenOrders.set(key, entries); +}; +const paramsOfPromise = new WeakMap, any[]>(); +// The cacheKey a request was made under; the option may have changed by the time it answers. +const keyOfParams = new WeakMap(); +// Params of the latest request under each key: the page a new reader starts from. +const latestParamsOfKey = new Map(); + const useCachePlugin: Plugin = ( fetchInstance, { @@ -18,23 +47,61 @@ const useCachePlugin: Plugin = ( }, ) => { const unSubscribeRef = useRef<() => void>(undefined); + const subscribedKeyRef = useRef(undefined); const currentPromiseRef = useRef>(undefined); - const _setCache = (key: string, cachedData: CachedData) => { + // Without params: the page of the latest request, or nothing while it is still loading. + // With params: that page only. + const _getCache = (key: string, params?: any[]) => { + if (customGetCache) { + return customGetCache(params ?? []); + } + const latestParams = latestParamsOfKey.get(key); + return getCache(key, params ?? latestParams); + }; + + // The store is asked what it holds for these params: a single-slot store answers with + // whatever page it has, a per-page store only for this page. A write is dropped when + // that entry came from a request that started later. + const _setCache = (key: string, cachedData: CachedData, order: number, notify = true) => { + const held = _getCache(key, cachedData.params); + const heldOrder = held && 'data' in held ? orderWrittenFor(key, held.params) : undefined; + if (heldOrder !== undefined && order < heldOrder) { + return; + } + recordWritten(key, cachedData.params, order); + const isLatest = order >= (lastWrittenOrder.get(key) ?? 0); + if (isLatest) { + lastWrittenOrder.set(key, order); + } if (customSetCache) { customSetCache(cachedData); } else { - setCache(key, cacheTime, cachedData); + setCache(key, cacheTime, cachedData, isLatest); + } + if (notify && isLatest) { + trigger(key, cachedData.data, cachedData.params); } - trigger(key, cachedData.data); }; - const _getCache = (key: string, params: any[] = []) => { - if (customGetCache) { - return customGetCache(params); - } - return getCache(key); + // A component that has params of its own only takes data requested with the same params. + const _subscribe = (key: string) => { + unSubscribeRef.current?.(); + subscribedKeyRef.current = key; + unSubscribeRef.current = subscribe(key, (data, params) => { + const ownParams = fetchInstance.state.params; + if (params && ownParams && !depsEqual(params, ownParams)) { + return; + } + fetchInstance.setState({ data }); + }); + }; + + const _unsubscribe = () => { + unSubscribeRef.current?.(); + unSubscribeRef.current = undefined; + subscribedKeyRef.current = undefined; }; useCreation(() => { @@ -53,13 +120,20 @@ const useCachePlugin: Plugin = ( } // subscribe same cachekey update, trigger update - unSubscribeRef.current = subscribe(cacheKey, (data) => { - fetchInstance.setState({ data }); - }); + _subscribe(cacheKey); }, []); + // Follow the key currently rendered, so a change of cacheKey drops the old key's updates. + if (cacheKey !== subscribedKeyRef.current) { + if (cacheKey) { + _subscribe(cacheKey); + } else { + _unsubscribe(); + } + } + useUnmount(() => { - unSubscribeRef.current?.(); + _unsubscribe(); }); if (!cacheKey) { @@ -93,44 +167,86 @@ const useCachePlugin: Plugin = ( onRequest: (service, args) => { let servicePromise = getCachePromise(cacheKey); - // If has servicePromise, and is not trigger by self, then use it - if (servicePromise && servicePromise !== currentPromiseRef.current) { - return { servicePromise }; + // If has servicePromise for the same params, and is not trigger by self, then use it + if ( + servicePromise && + servicePromise !== currentPromiseRef.current && + depsEqual(paramsOfPromise.get(servicePromise), args) + ) { + // A shared request is as old as the one that started it. + const sharedOrder = orderOfPromise.get(servicePromise) ?? ++requestOrder; + orderOfParams.set(args, sharedOrder); + keyOfParams.set(args, cacheKey); + latestParamsOfKey.set(cacheKey, args); + // A newer request for the same params may have written before this one settles. + return { + servicePromise: servicePromise.then((data) => { + const held = _getCache(cacheKey, args); + const heldOrder = + held && 'data' in held && depsEqual(held.params, args) + ? orderWrittenFor(cacheKey, args) + : undefined; + return heldOrder !== undefined && heldOrder > sharedOrder ? held.data : data; + }), + }; } servicePromise = service(...args); + const order = ++requestOrder; + orderOfPromise.set(servicePromise, order); + paramsOfPromise.set(servicePromise, args); + orderOfParams.set(args, order); + keyOfParams.set(args, cacheKey); + latestParamsOfKey.set(cacheKey, args); currentPromiseRef.current = servicePromise; setCachePromise(cacheKey, servicePromise); return { servicePromise }; }, - onSuccess: (data, params) => { - if (cacheKey) { - // cancel subscribe, avoid trgger self - unSubscribeRef.current?.(); - _setCache(cacheKey, { + onSuperseded: (data, params) => { + // Stored for later reads, but never pushed to components waiting on a newer request. + _setCache( + keyOfParams.get(params) ?? cacheKey, + { data, params, time: Date.now(), - }); + }, + orderOfParams.get(params) ?? 0, + false, + ); + }, + onSuccess: (data, params) => { + if (cacheKey) { + // cancel subscribe, avoid trgger self + _unsubscribe(); + _setCache( + keyOfParams.get(params) ?? cacheKey, + { + data, + params, + time: Date.now(), + }, + orderOfParams.get(params) ?? ++requestOrder, + ); // resubscribe - unSubscribeRef.current = subscribe(cacheKey, (d) => { - fetchInstance.setState({ data: d }); - }); + _subscribe(cacheKey); } }, onMutate: (data) => { if (cacheKey) { // cancel subscribe, avoid trigger self - unSubscribeRef.current?.(); - _setCache(cacheKey, { - data, - params: fetchInstance.state.params, - time: Date.now(), - }); + _unsubscribe(); + _setCache( + cacheKey, + { + data, + params: fetchInstance.state.params, + time: Date.now(), + }, + ++requestOrder, + ); // resubscribe - unSubscribeRef.current = subscribe(cacheKey, (d) => { - fetchInstance.setState({ data: d }); - }); + _subscribe(cacheKey); } }, }; diff --git a/packages/hooks/src/useRequest/src/types.ts b/packages/hooks/src/useRequest/src/types.ts index 2e0eabd3..4de36d0f 100644 --- a/packages/hooks/src/useRequest/src/types.ts +++ b/packages/hooks/src/useRequest/src/types.ts @@ -30,6 +30,8 @@ export interface PluginReturn { }; onSuccess?: (data: TData, params: TParams) => void; + /** A request resolved after a newer call or `cancel()` made its result unused. */ + onSuperseded?: (data: TData, params: TParams) => void; onError?: (e: Error, params: TParams) => void; onFinally?: (params: TParams, data?: TData, e?: Error) => void; onCancel?: () => void; diff --git a/packages/hooks/src/useRequest/src/utils/cache.ts b/packages/hooks/src/useRequest/src/utils/cache.ts index d16f9604..e023f372 100644 --- a/packages/hooks/src/useRequest/src/utils/cache.ts +++ b/packages/hooks/src/useRequest/src/utils/cache.ts @@ -1,3 +1,5 @@ +import { depsEqual } from '../../../utils/depsEqual'; + type Timer = ReturnType; type CachedKey = string | number; @@ -10,7 +12,8 @@ interface RecordData extends CachedData { timer: Timer | undefined; } -const cache = new Map(); +// One record per params under each key; the first record is the newest page. +const cache = new Map(); const clearTimer = (cachedData?: RecordData) => { if (cachedData?.timer) { @@ -18,40 +21,74 @@ const clearTimer = (cachedData?: RecordData) => { } }; -const setCache = (key: CachedKey, cacheTime: number, cachedData: CachedData) => { - const currentCache = cache.get(key); - clearTimer(currentCache); +const removeRecord = (key: CachedKey, record: RecordData) => { + const records = cache.get(key); + if (!records) { + return; + } + const index = records.indexOf(record); + if (index > -1) { + records.splice(index, 1); + } + if (!records.length) { + cache.delete(key); + } +}; - let timer: Timer | undefined = undefined; +// `latest` false keeps the record out of the first slot: an older page that answers +// late is kept for its own params without becoming the page a new reader starts from. +const setCache = ( + key: CachedKey, + cacheTime: number, + cachedData: CachedData, + latest: boolean = true, +) => { + const records = cache.get(key) ?? []; + const index = records.findIndex((record) => depsEqual(record.params, cachedData.params)); + if (index > -1) { + clearTimer(records[index]); + records.splice(index, 1); + } + + const record: RecordData = { ...cachedData, timer: undefined }; if (cacheTime > -1) { // if cache out, clear it - timer = setTimeout(() => { - cache.delete(key); + record.timer = setTimeout(() => { + removeRecord(key, record); }, cacheTime); } - cache.set(key, { - ...cachedData, - timer, - }); + if (latest || index === -1) { + records.splice(latest ? 0 : records.length, 0, record); + } else { + records.splice(index, 0, record); + } + cache.set(key, records); }; -const getCache = (key: CachedKey) => { - return cache.get(key); +// Without params, the newest record of the key; with params, the record for those params. +const getCache = (key: CachedKey, params?: any[]) => { + const records = cache.get(key); + if (!records?.length) { + return undefined; + } + if (!params) { + return records[0]; + } + return records.find((record) => depsEqual(record.params, params)); }; const clearCache = (key?: string | string[]) => { if (key) { const cacheKeys = Array.isArray(key) ? key : [key]; cacheKeys.forEach((cacheKey) => { - const currentCache = cache.get(cacheKey); - clearTimer(currentCache); + cache.get(cacheKey)?.forEach(clearTimer); cache.delete(cacheKey); }); } else { - for (const currentCache of cache.values()) { - clearTimer(currentCache); + for (const records of cache.values()) { + records.forEach(clearTimer); } cache.clear(); } diff --git a/packages/hooks/src/useRequest/src/utils/cachePromise.ts b/packages/hooks/src/useRequest/src/utils/cachePromise.ts index e654aa44..a5055324 100644 --- a/packages/hooks/src/useRequest/src/utils/cachePromise.ts +++ b/packages/hooks/src/useRequest/src/utils/cachePromise.ts @@ -10,15 +10,20 @@ const setCachePromise = (cacheKey: CachedKey, promise: Promise) => { // Because the promise.finally will change the reference of the promise cachePromise.set(cacheKey, promise); + // A newer request may have taken the key since; only remove our own entry. + const remove = () => { + if (cachePromise.get(cacheKey) === promise) { + cachePromise.delete(cacheKey); + } + }; + // no use promise.finally for compatibility promise .then((res) => { - cachePromise.delete(cacheKey); + remove(); return res; }) - .catch(() => { - cachePromise.delete(cacheKey); - }); + .catch(remove); }; export { getCachePromise, setCachePromise }; diff --git a/packages/hooks/src/useRequest/src/utils/cacheSubscribe.ts b/packages/hooks/src/useRequest/src/utils/cacheSubscribe.ts index 84f690d7..05190c39 100644 --- a/packages/hooks/src/useRequest/src/utils/cacheSubscribe.ts +++ b/packages/hooks/src/useRequest/src/utils/cacheSubscribe.ts @@ -1,9 +1,9 @@ -type Listener = (data: any) => void; +type Listener = (data: any, params?: any[]) => void; const listeners: Record = {}; -const trigger = (key: string, data: any) => { +const trigger = (key: string, data: any, params?: any[]) => { if (listeners[key]) { - listeners[key].forEach((item) => item(data)); + listeners[key].forEach((item) => item(data, params)); } }; REFERENCE_PATCH