diff --git a/README.md b/README.md index 86c80fc..6838c01 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,9 @@ The options available are: - `executionTime`: The execution time of the current function execution in milliseconds. - `args`: The arguments passed to the current function. - `timeFrameCacheRecords`: The cache records of the last `timeFrame` milliseconds. +- `customKeyFunction` (_optional_): A function to generate a custom key for every cache record. + The function receives the arguments passed to the current function and should return a string. + If not passed, the key will be generated based on an internal algorithm that considers the arguments passed to the function. - `millisecondThreshold` (_optional_): The threshold in milliseconds to be considered for the condition checks. If not passed, this criteria will be ignored. - `requestsThreshold` (_optional_): The number of requests to be considered for the condition checks. Default: `1`. - `expirationMode` (_optional_): The expiration mode to use. Default: `default`. diff --git a/src/index.test.ts b/src/index.test.ts index 63143ea..e95f3e9 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -222,6 +222,22 @@ describe('Higher-Order Function', () => { await sleep(TTL + EXECUTION_MARGIN); expect(eventHits.get('onCacheHit')).toBe(1); }); + + it('should allow for custom getDataCacheKey functions', async () => { + const mockFn = jest.fn(); + const wrappedMockFn = cacheCandidate(mockFn, { + customKeyFunction: (args) => { + return 'custom-key'; + }, + events: { + onCacheSet: ({key}) => { + expect(key).toBe('custom-key'); + } + } + }); + wrappedMockFn(1); + await sleep(TTL + EXECUTION_MARGIN); + }); }); describe('Library-wide Conditions', () => { diff --git a/src/lib.ts b/src/lib.ts index a54bad7..bf6e030 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -111,7 +111,7 @@ export function cacheCandidate Promise>( return function cacheCandidateWrapper(...args: Parameters): ReturnType { return letsCandidate({ options, - key: getDataCacheKey([uniqueIdentifier, JSON.stringify(args)]), + key: _options.customKeyFunction ? _options.customKeyFunction(args) : getDataCacheKey([uniqueIdentifier, JSON.stringify(args)]), timeoutCache, runningQueryCache, timeframeCache, diff --git a/src/models.ts b/src/models.ts index 507298e..6024322 100644 --- a/src/models.ts +++ b/src/models.ts @@ -17,6 +17,7 @@ export interface CacheCandidateInputOptions { ttl?: number; timeFrame?: number; candidateFunction?: (CandidateFunctionOptions) => boolean; + customKeyFunction?: (args: any) => string; millisecondThreshold?: number; requestsThreshold?: number; expirationMode?: 'default' | 'timeout-only' | 'eject';