Skip to content

Commit

Permalink
Merge pull request #1 from cajames/onhit
Browse files Browse the repository at this point in the history
  • Loading branch information
cajames committed Feb 3, 2021
2 parents 4f3d3ce + dac2e42 commit f66989e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/__tests__/lib.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,23 @@ describe("memorise", () => {
expect(testFn).toHaveBeenCalledTimes(1);
});

it("should call the onHit handler if passed in", () => {
const testFn = jest.fn().mockReturnValue("success");
const onHitFn = jest.fn();
const cachedFn = memorise(testFn, {
onHit: onHitFn,
});

cachedFn();
expect(testFn).toHaveBeenCalledTimes(1);
expect(onHitFn).toHaveBeenCalledTimes(0);

cachedFn();
expect(testFn).toHaveBeenCalledTimes(1);
expect(onHitFn).toHaveBeenCalledTimes(1);
expect(onHitFn).toHaveBeenCalledWith("", "success", cachedFn._cache);
});

// Later features
xit("should not cache a promise rejection when configured not to", async () => {});
xit("should cache an error when configured to", async () => {});
Expand Down
26 changes: 25 additions & 1 deletion src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,27 @@ export interface MemorisedOptions<
T extends any = any,
ARGS extends any[] = any[]
> {
cache?: Lru<T>;
/**
* Optional cache passed in.
*/
cache?: any;
/**
* Cache Key resolver based on arguments to function
*/
cacheKeyResolver?: (...args: ARGS) => string;
/**
* Optional callback called when a cache value is hit.
*
* @param cacheKey The key that was hit
* @param value The value that was returned by the cache
* @param cache The cache
*/
onHit?: (cacheKey: string, value: T, cache: Lru<T>) => void;

/**
* Options passed to internal `tiny-lru` cache that will be created.
* Not used if `cache` is passed in.
*/
lruOptions?: LRUOptions;
}

Expand All @@ -36,6 +55,7 @@ export const memorise = <RESULT extends any = any, ARGS extends any[] = any[]>(
const {
cache,
cacheKeyResolver = defaultGenCacheKey,
onHit,
lruOptions = {
max: 1000,
},
Expand All @@ -50,6 +70,10 @@ export const memorise = <RESULT extends any = any, ARGS extends any[] = any[]>(

// If cached value, return it
if (cachedValue !== undefined) {
// If onHit handler is there, run it
if (onHit) {
onHit(cacheKey, cachedValue, _cache);
}
return cachedValue;
}

Expand Down

0 comments on commit f66989e

Please sign in to comment.