Commit 8788cc69 authored by nanahira's avatar nanahira

support @CacheKey() on getter

parent 0dc9c729
...@@ -22,18 +22,27 @@ const DrainKey = ...@@ -22,18 +22,27 @@ const DrainKey =
( (
fun: ObjectAndKeyFunction<T> = defaultValue, fun: ObjectAndKeyFunction<T> = defaultValue,
): PropertyDecorator & TypedMethodDecorator<ObjectFunction<T>> => ): PropertyDecorator & TypedMethodDecorator<ObjectFunction<T>> =>
(obj, key, des?) => { (target: any, key: string, descriptor?: PropertyDescriptor) => {
let cb: ObjectFunction<T>; let cb: ObjectFunction<T>;
if (des) {
// method decorator if (descriptor) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // method decorator: descriptor.value
// @ts-ignore if (typeof descriptor.value === 'function') {
cb = async (o) => fun(await o[key](), key); cb = async (o) => fun(await descriptor.value.call(o), key);
}
// getter/accessor decorator: descriptor.get
else if (typeof descriptor.get === 'function') {
cb = async (o) => fun(await descriptor.get.call(o), key);
} else {
// unlikely: setter-only accessor etc.
cb = async (o) => fun(await (o as any)[key], key);
}
} else { } else {
// property decorator // property decorator
cb = (o) => fun(o[key], key); cb = (o) => fun((o as any)[key], key);
} }
return decoratorFactory(cb)(obj.constructor);
return decoratorFactory(cb)((target as any).constructor);
}; };
export const CacheKey = DrainKey<string>( export const CacheKey = DrainKey<string>(
......
...@@ -205,4 +205,37 @@ describe('Aragami.', () => { ...@@ -205,4 +205,37 @@ describe('Aragami.', () => {
expect(_task2.id).toBe(1); expect(_task2.id).toBe(1);
await expect(aragami.queueLength(Task)).resolves.toBe(0); await expect(aragami.queueLength(Task)).resolves.toBe(0);
}); });
it('should support @CacheKey() on getter', async () => {
@CachePrefix('profile')
@CacheTTL(100)
class Profile {
id!: number;
name!: string;
@CacheKey()
get cacheKey() {
return `id.${this.id}`;
}
}
await aragami.clear(Profile);
const p = new Profile();
p.id = 42;
p.name = 'Karin';
await expect(aragami.set(p)).resolves.toEqual(p);
// key derived from getter
await expect(aragami.has(p)).resolves.toBeTruthy();
await expect(aragami.has(Profile, 'id.42')).resolves.toBeTruthy();
await expect(aragami.has('profile', 'id.42')).resolves.toBeTruthy();
const got = await aragami.get(Profile, 'id.42');
expect(got).toBeInstanceOf(Profile);
expect(got).toEqual({ id: 42, name: 'Karin' });
await expect(aragami.keys(Profile)).resolves.toEqual(['id.42']);
});
}); });
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment