toss / nestjs-aop

A way to gracefully apply AOP to nestjs
MIT License
213 stars 24 forks source link

feat: Add 'init' into 'LazyDecorator' for providing metadata to decorated target when 'onModuleInit()'. #31

Closed Revimal closed 7 months ago

Revimal commented 8 months ago

Overview

I found a limitation of the wrap method of LazyDecorator; advice logic can only be triggered by calling the decorated method. I wanted to reference the metadata of the decorated method in NestInterceptor but couldn't get the correct metadata value even with reflection until the method was first called. I implemented an additional prototype, init for LazyDecorator, called when AopModule is initialized.

PR Checklist

  1. I have read the Contributing Guide
  2. I have written documents and tests, if needed.
Revimal commented 7 months ago

I had some misunderstanding about the implementation of 'nestjs-aop.' I'll try to add metadata in the 'wrap' method in another way. Closing this PR for now.

WhiteKiwi commented 7 months ago

I'm sorry for the late confirmation. I'm glad to hear that you've solved it

Revimal commented 7 months ago

@WhiteKiwi I've tried to add metadata using LazyDecorator as the form below, but it's still not applied until the first execution of the decorated method.

@Aspect(HTTP_TIMEOUT_ASPECT)
export class HttpTimeoutAspect implements LazyDecorator<any, HttpTimeoutOptions> {
  wrap(params: WrapParams<Function, HttpTimeoutOptions>) {
    const unboundMethod = params.instance[params.methodName];
    Reflect.defineMetadata(HTTP_TIMEOUT_METADATA, params.metadata.timeoutAsMilliseconds, unboundMethod);
    Reflect.defineMetadata(HTTP_TIMEOUT_INFORMATION, {
      methodName: params.methodName,
      methodArgs: args.map(arg => JSON.stringify(decycleObject(arg))),
    } as HttpTimeoutInformation, unboundMethod);

    return async (...args: any[]) => {
      return await params.method(...args);
    }
  }
}

Therefore, I'm supposed to re-open this PR to solve this issue.

Before it, I'd like some affirmation about the purpose of this repo, 'nestjs-aop'. Was it only developed for applying an advice logic such as 'Around Advice', not general method decorating? If that is so, I'll find another way to fix it besides using this repository.

WhiteKiwi commented 7 months ago

Currently, the LazyDecorator.wrap in nestjs-aop is executed by the first call. It could be improved to be called at creation, but I haven't worked on it due to the complexity of the code and the low necessity for such a feature.

Having looked at the example you provided above, it appears that using TypeScript decorator should be sufficient. I am curious to know what specific issues are being encountered with this approach.