【发布时间】:2021-10-17 00:48:43
【问题描述】:
我正在开发一个 NestJS 项目, 我正在尝试在记录器中访问 executionContext 以按请求过滤日志。
每个可注射物都有一个记录器实例,我想保持这种行为(因此可注射物的范围是默认值)。
为此,我尝试创建一个装饰器,从请求中获取上下文并将其传递给子服务(如在记录器中),以最终在记录器中获取上下文...
我不确定...现在,这是我的代码:
export const Loggable = () => (constructor: Function) => {
for (const propertyName of Reflect.ownKeys(constructor.prototype)) {
let descriptor = Reflect.getOwnPropertyDescriptor(constructor.prototype, propertyName);
const isMethod = descriptor.value instanceof Function;
if (!isMethod)
continue;
const originalMethod = descriptor.value;
const routeArgsMetada = Reflect.getMetadata(ROUTE_ARGS_METADATA, constructor, propertyName as string);
descriptor.value = function (...args: any[]) {
const result = originalMethod.apply(this, args);
//TODO : retrieve the request / contextExecution
//TODO : pass the request / contextExecution to children functions...
return result;
};
Reflect.defineProperty(constructor.prototype, propertyName, descriptor);
Reflect.defineMetadata(ROUTE_ARGS_METADATA, routeArgsMetada, constructor, propertyName as string);
}
};
这个@Loggable() 装饰器将附加到所有需要记录或抛出执行上下文的可注入类
这可能吗?如果不是为什么?
PS:我想知道,@Guard 注释如何获取上下文? @Req 注解如何获取请求?
https://github.com/nestjs/nest/tree/master/packages/common/decorators/http
https://github.com/nestjs/nest/blob/master/packages/common/decorators/core/use-guards.decorator.ts
【问题讨论】:
-
我认为使用您在此处布置的装饰器方法是不可能的。你为什么不为此使用一个自动访问上下文的拦截器?
-
目标是在记录器服务中获取上下文。如果有可能将它从拦截器扔到服务中,我没有得到解决方案......
标签: node.js typescript express nestjs typescript-decorator