Skip to content

Commit 8e454c9

Browse files
committed
feat(cache): adds eviction method to cached functions
1 parent ba0c3f6 commit 8e454c9

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/services/common/base-client.ts

+17-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { RecursiveRecord } from '~/utils/typescript.utils';
55
import { CancellableFetch, type CancellablePromise } from '~/utils/fetch.utils';
66
import { HttpMethod, type HttpMethods } from '~/utils/http.utils';
77
import { Observable, ObservableState, type Observer, type Updater } from '~/utils/observable.utils';
8+
import { ExactMatchRegex } from '~/utils/regex.utils';
89

910
export const BaseApiHeaders = {
1011
/** The authorization token bearer */
@@ -192,15 +193,17 @@ export const getCachedFunction = <
192193
clientFn: ClientEndpointCall<Parameter, ResponseBody>,
193194
{
194195
key,
196+
evictionKey,
195197
cache,
196198
retention,
197199
}: {
198200
key: string | ((param?: Parameter, init?: BaseInit) => string);
201+
evictionKey?: string | ((param?: Parameter, init?: BaseInit) => string);
199202
cache: CacheStore<ResponseType>;
200203
retention?: BaseTemplateOptions['cache'];
201204
},
202205
): ClientEndpointCache<Parameter, ResponseBody> => {
203-
return async (param, init, cacheOptions) => {
206+
const cachedFn: ClientEndpointCache<Parameter, ResponseBody> = async (param, init, cacheOptions) => {
204207
const _key = typeof key === 'function' ? key(param, init) : key;
205208
const cached = await cache.get(_key);
206209
if (cached && !cacheOptions?.force) {
@@ -228,6 +231,18 @@ export const getCachedFunction = <
228231
throw error;
229232
}
230233
};
234+
235+
const evictFn = async (param?: Parameter, init?: BaseInit) => {
236+
const _key = evictionKey ?? key;
237+
if (!_key) return;
238+
const _resolvedKey = typeof _key === 'function' ? _key(param, init) : _key;
239+
if (!_resolvedKey.trim()) return;
240+
await cache.clear(_resolvedKey);
241+
return _resolvedKey;
242+
};
243+
244+
Object.defineProperty(cachedFn, 'evict', { value: evictFn });
245+
return cachedFn;
231246
};
232247

233248
/**
@@ -336,6 +351,7 @@ export abstract class BaseClient<
336351
key: (param: unknown, init: unknown) => JSON.stringify({ template: template.config, param, init }),
337352
cache: this._cache,
338353
retention: template.opts?.cache,
354+
evictionKey: `{"template":${JSON.stringify(template.config).replace(ExactMatchRegex, '\\$&')}`,
339355
});
340356

341357
const parseUrl = (param: Record<string, unknown> = {}) => {

0 commit comments

Comments
 (0)