我使用nestjs拦截器将控制器返回的数据放入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 })
中,但还要以某种方式指定类data
的{{1}}属性应为Intercepted
类型。
我试图创建一个这样的自定义装饰器:
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
时,它以某种方式工作(带有打字稿警告),但是它覆盖了我所有的sagger语言文档中的所有值,成为最后一个传递给({ {1}}。
我知道我可以为每种嵌套数据类型创建一个类,但是有没有更清洁的解决方案?
谢谢您的时间
答案 0 :(得分:0)
一种选择是使用您的自定义装饰器动态传递Swagger模式。在nestjs / terminus中,已经完成了非常类似的操作-请参见health-check.decorator.ts
和health-check.schema.ts
。
简而言之,您可以通过chmod
选项传递自定义。
schema