如何通过嵌套类输入@ApiOkResponse或创建适当的自定义装饰器? 控制器返回被拦截后返回

背景:

我使用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}}。

我知道我可以为每种嵌套数据类型创建一个类,但是有没有更清洁的解决方案?

谢谢您的时间

xuan1 回答:如何通过嵌套类输入@ApiOkResponse或创建适当的自定义装饰器? 控制器返回被拦截后返回

一种选择是使用您的自定义装饰器动态传递Swagger模式。在nestjs / terminus中,已经完成了非常类似的操作-请参见health-check.decorator.tshealth-check.schema.ts

简而言之,您可以通过chmod选项传递自定义。

schema
本文链接:https://www.f2er.com/2460113.html

大家都在问