feat: Cache decorator

This commit is contained in:
linyuchen 2024-05-15 17:55:03 +08:00
parent 763cac8532
commit d14ba3f0f7

View File

@ -35,3 +35,34 @@ export function truncateString(obj: any, maxLength = 500) {
}
return obj;
}
/**
* key生成缓存键
* @param ttl
* @param customKey
* @returns
*/
export function cacheFunc(ttl: number, customKey: string='') {
const cache = new Map<string, { expiry: number; value: any }>();
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor): PropertyDescriptor {
const originalMethod = descriptor.value;
const className = target.constructor.name; // 获取类名
const methodName = propertyKey; // 获取方法名
descriptor.value = async function (...args: any[]){
const cacheKey = `${customKey}${className}.${methodName}:${JSON.stringify(args)}`;
const cached = cache.get(cacheKey);
if (cached && cached.expiry > Date.now()) {
return cached.value;
} else {
const result = await originalMethod.apply(this, args);
cache.set(cacheKey, { value: result, expiry: Date.now() + ttl });
return result;
}
};
return descriptor;
};
}