我使用 NestJS 和 Nestjs/swagger 模块来获取简单的 api 文档,但我遇到了麻烦,因为我需要验证服务的响应。
这就是我创建自制方法装饰器的原因,但是当我使用它时,我遇到了很大的麻烦 - 来自另一个装饰器的所有元数据都丢失了,并且 swagger 模块无法显示良好的文档。
我的装饰器的代码
export function validate(classValidatorEntity: any): MethodDecorator {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const origMethod = descriptor.value;
descriptor.value = async function() {
const result = await origMethod.apply(this, arguments);
console.log(result); // validationFunc(result) in original method
return result;
};
};
}
以及一些控制器方法的代码示例
@Post('test')
@ApiOkResponse({
type: someResDto
})
@ResponseValidator(ActualizeFlightQueueResponseDto)
public async test(@Body() body: someReqDto): Promise<someResDto> {
return {result: true}
}
如果我的装饰器位于顶部(第一个)-所有元数据都会丢失。
如果我的装饰器是最后一个 - 我会丢失来自 @Body() 装饰器的数据......
我不知道该怎么做,也不知道如何重写我自己的装饰器。
元数据与特定的descriptor.value
,您必须重新应用与origMethod
到新的descriptor.value
首先定义一个元数据copyMetadata
method
const copyMetadata = (source: Object, target: Object): void => {
for (const key of Reflect.getMetadataKeys(source)) {
Reflect.defineMetadata(key, Reflect.getMetadata(key,source), target);
}
}
然后将元数据重新应用到新的descriptor.value
export function validate(classValidatorEntity: any): MethodDecorator {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const origMethod = descriptor.value;
descriptor.value = async function() {
const result = await origMethod.apply(this, arguments);
console.log(result); // validationFunc(result) in original method
return result;
};
copyMetadata(origMethod, descriptor.value);
};
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)