最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NestJSswagger: what model is the ApiExtraModel expecting as a parameter? - Stack Overflow

programmeradmin1浏览0评论

The @nestjs/swagger doc describes here that defining an extra model should be done this way:

@ApiExtraModels(ExtraModel)
export class CreateCatDto {}

But what is ExtraModel here ? The doc is not very clear about this.

The @nestjs/swagger doc describes here that defining an extra model should be done this way:

@ApiExtraModels(ExtraModel)
export class CreateCatDto {}

But what is ExtraModel here ? The doc is not very clear about this.

Share Improve this question asked Apr 10, 2020 at 15:16 benterrisbenterris 8511 gold badge10 silver badges19 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 7

Worked for me, when I've set @ApiExtraModels(MyModelClass) on the top of controller.

Thanks for this topic and also to this comment in GitHub issue.

I don't want to list all models in extraModels array in SwaggerModule.createDocument, so this is a great solution for me.

I ran into the same uncertainity. After googling https://github.com/nestjs/swagger/pull/355/files I understood the documentation:

  • first import your model to be referred to by import { ExtraModel } from '<filename>' (<--- so this is lacking in the docs BTW)
  • then provide it as param 'ExtraModel' to the decorator
  • the decorator then decorates the class which refers to the model (so providing the reference)

I guess you had the same mind-twister as me that the ApiExtraModels-decorator acts on the model ...

Cheers, Stephan

For those still wondering. For the example given in NestJs docs (https://docs.nestjs.com/openapi/types-and-parameters#oneof-anyof-allof )

@ApiExtraModels(ExtraModel)
export class CreateCatDto {

@ApiProperty({
  type: 'array',
  items: {
    oneOf: [
      { $ref: getSchemaPath(Cat) },
      { $ref: getSchemaPath(Dog) },
    ],
  },
})
pets: Pet[];
}

In case you DTO is 'CreateCatDto' and you want to use a separate 'Cat' and 'Dog' Dto that might be in same or other file you need to do the following.

@ApiExtraModels(Cat)
@ApiExtraModels(Dog)
export class CreateCatDto {

@ApiProperty({
  type: 'array',
  items: {
    oneOf: [
      { $ref: getSchemaPath(Cat) },
      { $ref: getSchemaPath(Dog) },
    ],
  },
})
pets: Pet[];
}

In here the ExtraModel is nothing but the DTOs that we are using and we need to add them above the DTO that we want them to extend, if we are using them in the CreateCatDto like the example above.

And in case of parameter or ApiProperty defined in Controller, simply add the ApiExtraMode() on top of the controller. [Answered previously]

发布评论

评论列表(0)

  1. 暂无评论