Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty JSON parameters for array POST in swagger

I'm using nest.js and I have a post route to add new news to database so I used postman to send array of objects like this:

[
{ 
    "newsTitle" : "title1",
    "newsDescription": "description1"
},
{ 
    "newsTitle" : "title2",
    "newsDescription": "description2"
}
]

and this the code for post in my controller:

@Post()
  async create(@Body() body: NewsDto[]) {

    const len = body.length;

    if (len == 1) {
    }

    else if (len > 1) {
    }

    return this.newsService.createNews(body);
  }

so everything work fine in post and saving data in database but when I use swagger I get the Model of for the dto of this controller like this:

enter image description here

You can see that the the parameters of dto not displayed here and I get the "Array" title instead because I use @Body() body: NewsDto[] and it's array as you see

enter image description here

also here in the post I can't get the JSON so I can add it or post it in another word

so how to handle this so when the length of array only 1 object then I return NewsDto parameters and if the length of array more than 1 object so return the NewsDto parameters too instead of Array?

like image 602
muklah Avatar asked Nov 18 '25 04:11

muklah


1 Answers

You have to add the @ApiModelProperty() decorator to your DTO's properties:

export class NewsDto {
  @ApiModelProperty()
  newsTitle: string;

  @ApiModelProperty()
  newsDescription: string;
}

Then add @ApiImplicitBody() to the controller method:

@Post()
@ApiImplicitBody({ name: 'news', type: [NewsDto]})
async create(@Body('news') body: NewsDto[]) {
like image 125
Kim Kern Avatar answered Nov 19 '25 16:11

Kim Kern



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!