Mah*_*dad 2 node.js nestjs nestjs-fastify
这是我的装饰师
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
export const CacheData = createParamDecorator(
(data: any, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
console.log(request.url, request.method, 'request');
const response = ctx.switchToHttp().getResponse();
const reqBody = request.body;
console.log(reqBody, 'reqBody');
console.log(response.raw.req.data, 'response');
console.log(response.raw.req.body, 'response');
console.log(response.raw.data, 'response');
console.log(response.cacheData, 'response');
}
);
Run Code Online (Sandbox Code Playgroud)
在我的控制器函数中,我使用装饰器,如下所示:
getStringsArr(
@Headers('Authorization') auth: string,
@Headers('Country') country = 'DK',
@CacheData() cacheData,
): Array<string> {
return ['Hello', 'World', '!'];
}
Run Code Online (Sandbox Code Playgroud)
那么如何在 CacheData 装饰器中访问响应数据呢?
小智 5
您的CacheData装饰器是一个 param 装饰器,这意味着,据我所知,它只会在调用方法处理程序时执行。你有几个选择。这里有两个。
方法装饰器可以让您访问函数返回的数据,但也有缺点:与参数装饰器不同,您无权访问执行上下文,并且注入客户服务不太优雅。我喜欢这个选项,因为它很容易向装饰器提供参数。
由于您的示例是围绕缓存的,我怀疑您会想要在那里注入您的服务,因此选项 B 可能更适合您的要求,但这里有一个带有方法装饰器的实现:
const MyMethodDecorator = (params) => {
return (
target: Record<string, unknown>,
_propertyKey: string,
descriptor: PropertyDescriptor,
) => {
const originalMethod = descriptor.value;
descriptor.value = async function (...args) {
const data = await originalMethod.apply(this, args);
// data = ['Hello', 'World', '!']
};
return descriptor;
};
};
@MyMethodDecorator({ ttl: 120, cacheKey: 'stringsArr' })
getStringsArr(
@Headers('Authorization') auth: string,
@Headers('Country') country = 'DK'
): Array<string> {
return ['Hello', 'World', '!'];
}
Run Code Online (Sandbox Code Playgroud)
拦截器使依赖注入变得容易,因为它就像任何其他 NestJS 服务一样。如果您选择此选项,我建议您阅读并理解请求生命周期。
与装饰器相比,一个缺点是提供参数不太优雅,但可以使用反射和方法装饰器来实现:
import { applyDecorators, SetMetadata, UseInterceptors } from '@nestjs/common';
@Injectable()
export class MyInterceptor implements NestInterceptor {
constructor(private readonly reflector: Reflector) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const params = this.reflector.get('MyInterceptorMetadataKey', context.getHandler());
// params = { ttl: 120, cacheKey: 'stringsArr' }
return next.handle().pipe(
tap((response) => {
// data = ['Hello', 'World', '!']
}),
);
}
}
const MyMethodDecorator = (params) =>
applyDecorators(SetMetadata('MyInterceptorMetadataKey', params));
@UseInterceptors(MyInterceptor)
@MyMethodDecorator({ ttl: 120, cacheKey: 'stringsArr' })
getStringsArr(
@Headers('Authorization') auth: string,
@Headers('Country') country = 'DK'
): Array<string> {
return ['Hello', 'World', '!'];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4412 次 |
| 最近记录: |