Skip to content

Commit

Permalink
feat(cache): propagate self to custom cache keys
Browse files Browse the repository at this point in the history
Signed-off-by: Tomas Dvorak <[email protected]>
  • Loading branch information
Tomas2D committed Dec 10, 2024
1 parent df52337 commit 85a27d2
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/cache/decoratorCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type InputFn = AnyFn;
type TargetFn = AnyFn;
type Instance = NonNullable<any>;

type CacheKeyFn = (...args: any[]) => string;
type CacheKeyFn = (this: Instance, ...args: any[]) => string;

export interface CacheDecoratorOptions {
enabled: boolean;
Expand Down Expand Up @@ -138,7 +138,7 @@ export function Cache(_options?: Partial<CacheDecoratorOptions>) {
return invokeOriginal();
}

const inputHash = ctx.options.cacheKey(...args);
const inputHash = ctx.options.cacheKey.apply(this, args);
if (
!ctx.cache.has(inputHash) ||
(ctx.cache.get(inputHash)?.expiresAt ?? Infinity) < Date.now() // is expired check
Expand Down Expand Up @@ -224,10 +224,10 @@ Cache.getInstance = function getInstance<T extends NonNullable<unknown>>(
};
};

export const WeakRefKeyFn: CacheKeyFn = (() => {
export const WeakRefKeyFn = (() => {
const _lookup = new WeakMap();

return (...args: any[]) => {
const fn = (...args: any[]) => {
const chunks = args.map((value) => {
if (R.isObjectType(value) || R.isFunction(value)) {
if (!_lookup.has(value)) {
Expand All @@ -239,7 +239,13 @@ export const WeakRefKeyFn: CacheKeyFn = (() => {
});
return createHash(JSON.stringify(chunks));
};
})();
fn.from = <T>(cb: (self: T) => any[]) => {
return function (this: T) {
return cb(this).map(fn).join("#");
};
};
return fn;
})() satisfies CacheKeyFn;

export const ObjectHashKeyFn: CacheKeyFn = (...args: any[]) =>
hash(args, {
Expand Down

0 comments on commit 85a27d2

Please sign in to comment.