[英]How to pass nested class to type in @ApiOkResponse or create appropriate custom decorator?
我使用nestjs拦截器将从controller返回的数据放入data
属性中并添加一些其他属性。 现在我想使用反映嵌套属性的@ApiOkResponse
。
{
prop1: 'val1',
prop2: 'val2'
}
data: {
prop1: 'val1',
prop2: 'val2'
},
addedProp: 'addedVal'
我也说了两个类:
// Have many variations of similar classes (for different controllers (types of data)
class NotYetIntercepted {
@ApiProperty()
prop1: string;
@ApiProperty()
prop2: string;
}
class Intercepted<T = any> {
@ApiProperty()
data: T;
@ApiProperty()
addedProp: string;
}
现在我想将@ApiOkResponse({ type: Intercepted })
添加到我的控制器中,但还要以某种方式指定 class Intercepted
的data
属性应该是NotYetIntercepted
类型。
我尝试创建一个这样的自定义装饰器:
import { ValidateNested } from 'class-validator';
import { ApiProperty, ApiResponseOptions, ApiOkResponse } from '@nestjs/swagger';
import { Intercepted } from '@appnamespace/models';
import { Type } from 'class-transformer';
export const CustomApiOkResponse = (notYetIntercepted: Function, options?: Omit<ApiResponseOptions, 'type'>) => {
class InterceptedWithData extends Intercepted {
@ApiProperty()
@ValidateNested()
@Type(() => notYetIntercepted)
data: typeof notYetIntercepted;
}
return ApiOkResponse({
...options,
type: InterceptedWithData,
});
};
那没有用。 当我删除@Type() => notYetIntercepted)
并将data
设置为data: notYetIntercepted
它以某种方式工作(带有 typescript 警告)但它覆盖了我的 swagger 文档中的所有值到最后传递的值( @CustomApiOkResponse(AnotherNotYetIntercepted)
)。
我知道我可以为每个嵌套数据类型创建一个 class 但有更清洁的解决方案吗?
感谢您的时间
一种选择是使用您的自定义装饰器动态传递 Swagger 模式。 在nestjs/terminus 中做了一些非常相似的事情——参见health-check.decorator.ts
和health-check.schema.ts
。
简而言之,您可以通过schema
选项传递自定义定义。
export const CustomApiOkResponse = (notYetIntercepted: Function, options?: Omit<ApiResponseOptions, 'type'>) => {
return ApiOkResponse({
...options,
schema: {
// .. your Swagger Schema
}
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.