【发布时间】:2019-06-14 10:24:36
【问题描述】:
我正在尝试创建一个需要依赖注入的装饰器。 例如:
@Injectable()
class UserService{
@TimeoutAndCache(1000)
async getUser(id:string):Promise<User>{
// Make a call to db to get all Users
}
}
@TimeoutAndCache 返回一个新的 Promise,它执行以下操作:
- 如果调用时间超过 1000 毫秒,则返回拒绝,当调用完成时,它会存储到 redis(以便下次可以获取)。
- 如果调用时间少于 1000 毫秒,则直接返回结果
export const TimeoutAndCache = function timeoutCache(ts: number, namespace) {
return function log(
target: object,
propertyKey: string,
descriptor: TypedPropertyDescriptor<any>,
) {
const originalMethod = descriptor.value; // save a reference to the original method
descriptor.value = function(...args: any[]) {
// pre
let timedOut = false;
// run and store result
const result: Promise<object> = originalMethod.apply(this, args);
const task = new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (!timedOut) {
timedOut = true;
console.log('timed out before finishing');
reject('timedout');
}
}, ts);
result.then(res => {
if (timedOut) {
// store in cache
console.log('store in cache');
} else {
clearTimeout(timer);
// return the result
resolve(res);
}
});
});
return task;
};
return descriptor;
};
};
我需要注入一个 RedisService 来保存评估结果。 我可以将 Redis 服务注入到 UserService 的一种方法,但看起来有点难看。
【问题讨论】:
标签: dependency-injection nestjs