NestJs - 从自定义装饰器内的服务调用方法

NestJs - Calling a method from a service inside a Custom Decorator

基于此,我尝试在装饰器中实现另一个服务的功能。

这是我的尝试:

export function ClearCache() {
  const injectCacheService = Inject(CacheService);

  return (target: any, _: string, propertyDescriptor: PropertyDescriptor) => {
    injectCacheService(target, 'service'); // this is the same as using constructor(private readonly logger: LoggerService) in a class

    //get original method
    const originalMethod = propertyDescriptor.value;

    //redefine descriptor value within own function block
    propertyDescriptor.value = async function (...args: any[]) {
      try {
        console.log(this);
        const service: CacheService = this.service;
        service.clearCacheById(args[1]);

        return await originalMethod.apply(this, args);
      } catch (error) {
        console.error(error);
      }
    };
  };
}

但是我得到了Property 'service' does not exist on type 'PropertyDescriptor'.ts(2339)

知道我遗漏了什么吗?

更新:

tsconfig.json 有“严格”:真。如果启用,则“this”将严格使用 PropertyDescriptor 接口。

通过更改 tsconfig.json 中的 "strict": false 解决了这个问题。

如何重现?

不清楚您是否在使用 NestJS cache-manager wrapper,如果是这样,您需要在注入时使用提供者令牌,类型为缓存。

export function ClearCache() {
    
    const injector = Inject(CACHE_MANAGER)

    return (target: any, _key?: string | symbol, descriptor?: TypedPropertyDescriptor<any>) => {
        
        injector(target, 'cacheManager')

        const originalMethod = descriptor.value

        descriptor.value = async function (...args: any[]) {
            try {
                const service: Cache = this.cacheManager
                service.delete(args[1])
                return await originalMethod.apply(this, args)
            } catch (err) {
                console.error(err)
                return originalMethod(args)
            }
        }
    }
}

如果它是不同的服务,请确保您使用的是正确的提供商令牌,它在当前模块范围内并已实例化。如果它不在当前模块中,请检查它是全局的

Uploaded minimal repo of above code here.

更新:

tsconfig.json 有 "strict":true。如果启用,则“this”将严格使用 PropertyDescriptor 接口。

通过更改 tsconfig.json 中的 "strict": false 解决了问题。