简体   繁体   English

NestJS:如何使用另一个装饰器自动记录@MessagePattern 的输入数据?

[英]NestJS: How to automatically log @MessagePattern's input data with another decorator?

I have a Controller, which is called by external microservices using the ClientProxy.send<>() method, which sends a command that is recognized by the accompanying @MessagePattern decorator and executes that Controller function:我有一个 Controller,它由外部微服务使用 ClientProxy.send<>() 方法调用,该方法发送一个由随附的@MessagePattern 装饰器识别的命令并执行该 Controller ZC1C425268E68384F1AB45707C1457:

@Controller()
export class DataController {

  @CustomLogger()
  @MessagePattern({ cmd: 'storeData' })
  storeData(
    owner: string,
    dataType: string,
  ): void {

  }
}

Now, every time this Controller is called, I want to log exactly which command was called.现在,每次调用此 Controller 时,我都想准确记录调用了哪个命令。 I could simply hardcode Logger.log('storeData') in the storeData() function and do that for every next function, but is it possible to log the input of the @MessagePattern() with another decorator automatically, like for example with @CustomLogger which I would define myself?我可以简单地在 storeData() function 中硬编码 Logger.log('storeData') 并为每个下一个 function 执行此操作,但是是否可以使用另一个装饰器自动记录 @MessagePattern() 的输入,例如使用 @我会定义自己的CustomLogger? And if so, how?如果是这样,怎么办?

It is possible to combine decorators with applyDecorators() .可以将装饰器与applyDecorators()结合使用。

In your case you could create a LogMessage Decorator like this:在您的情况下,您可以像这样创建一个LogMessage装饰器:

// LogMessage.ts
const LogMessage = (cmd: string) => {
  const logger = new Logger('MessageLogger');
  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    const targetFunc = descriptor.value;
    descriptor.value = function (...args: any[]) {
      logger.log(`Message: ${cmd}`);
      targetFunc.apply(this, args);
    };
    return descriptor;
  };
};

export default LogMessage;

and combine it with MessagePattern inside a new decorator MessagePatternWithLog :并将它与 MessagePattern 结合在一个新的装饰器MessagePatternWithLog中:

// MessagePatternWithLog.ts
const MessagePatternWithLog = ({cmd: string}) => {
  return applyDecorators(LogMessage(cmd), MessagePattern({cmd}));
};

export default MessagePatternWithLog;

After that you can use it like every other Decorator:之后,您可以像其他所有装饰器一样使用它:

@Controller()
export class DataController {

  @MessagePatternWithLog({cmd: 'storeData'})
  storeData(
    owner: string,
    dataType: string,
  ): void {

  }
}

This code is not tested but derived from a working example.此代码未经测试,但源自工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM