Skip to content

Commit

Permalink
feat: pass cache metadata to getFreshValue
Browse files Browse the repository at this point in the history
in order to support dynamically changing chage properties while getting the value

fix #25
  • Loading branch information
Xiphe committed Jan 19, 2023
1 parent fa175f5 commit 9097718
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
26 changes: 26 additions & 0 deletions src/cachified.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,32 @@ describe('cachified', () => {
expect(await pValue2).toBe('TWO');
});

it('supports extending ttl during getFreshValue operation', async () => {
const cache = new Map<string, CacheEntry>();
const reporter = createReporter();
const getValue = (
getFreshValue: CachifiedOptions<string>['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<string, CacheEntry>();
const getValue = (
Expand Down
7 changes: 5 additions & 2 deletions src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@ export interface Cache {
delete: (key: string) => unknown | Promise<unknown>;
}

interface GetFreshValueContext {
metadata: CacheMetadata;
}
export const HANDLE = Symbol();
export type GetFreshValue<Value> = {
(): Promise<Value> | Value;
(context: GetFreshValueContext): Promise<Value> | Value;
[HANDLE]?: () => void;
};
export const MIGRATED = Symbol();
Expand Down Expand Up @@ -72,7 +75,7 @@ export interface CachifiedOptions<Value> {
*
* Can be async and must return fresh value or throw.
*
* @type {function(): Promise | Value} Required
* @type {function(context): Promise | Value} Required
*/
getFreshValue: GetFreshValue<Value>;
/**
Expand Down
2 changes: 1 addition & 1 deletion src/getFreshValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export async function getFreshValue<Value>(
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) {
Expand Down

0 comments on commit 9097718

Please sign in to comment.