diff --git a/src/cachified.spec.ts b/src/cachified.spec.ts index e756974..400f7f3 100644 --- a/src/cachified.spec.ts +++ b/src/cachified.spec.ts @@ -716,6 +716,32 @@ describe('cachified', () => { expect(await pValue2).toBe('TWO'); }); + it('supports extending ttl during getFreshValue operation', async () => { + const cache = new Map(); + const reporter = createReporter(); + const getValue = ( + getFreshValue: CachifiedOptions['getFreshValue'], + ) => + cachified({ + cache, + ttl: 5, + key: 'test', + reporter, + getFreshValue, + }); + + expect( + await getValue(({ metadata }) => { + metadata.ttl = 10; + return 'ONE'; + }), + ).toBe('ONE'); + + currentTime = 6; + + expect(await getValue(() => 'TWO')).toBe('ONE'); + }); + it('resolves earlier pending values with faster responses from later calls', async () => { const cache = new Map(); const getValue = ( diff --git a/src/common.ts b/src/common.ts index 8f1814a..2ea5bf6 100644 --- a/src/common.ts +++ b/src/common.ts @@ -26,9 +26,12 @@ export interface Cache { delete: (key: string) => unknown | Promise; } +interface GetFreshValueContext { + metadata: CacheMetadata; +} export const HANDLE = Symbol(); export type GetFreshValue = { - (): Promise | Value; + (context: GetFreshValueContext): Promise | Value; [HANDLE]?: () => void; }; export const MIGRATED = Symbol(); @@ -72,7 +75,7 @@ export interface CachifiedOptions { * * Can be async and must return fresh value or throw. * - * @type {function(): Promise | Value} Required + * @type {function(context): Promise | Value} Required */ getFreshValue: GetFreshValue; /** diff --git a/src/getFreshValue.ts b/src/getFreshValue.ts index 0df72d9..757ccf7 100644 --- a/src/getFreshValue.ts +++ b/src/getFreshValue.ts @@ -14,7 +14,7 @@ export async function getFreshValue( let value: unknown; try { report({ name: 'getFreshValueStart' }); - const freshValue = await getFreshValue(); + const freshValue = await getFreshValue({ metadata: context.metadata }); value = freshValue; report({ name: 'getFreshValueSuccess', value: freshValue }); } catch (error) {