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

希克维内

基于此答案,我尝试从装饰器内的另一个服务实现一个功能。

这是我的尝试:

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 具有“严格”:true。如果启用,则“this”将严格使用 PropertyDescriptor 接口。

通过更改 tsconfig.json 中的 "strict": false 修复了该问题。

如何繁殖?

  • 在 tsconfig.json 上使用 "strict":true
极客

不清楚您是否使用 NestJS缓存管理器包装器,如果是这样,您需要在注入时使用提供者令牌,并且类型为 Cache。

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)
            }
        }
    }
}

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

在此处上传了上述代码的最小存储库

更新:

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

通过更改"strict": falsetsconfig.json修复了该问题

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章