I'm setting up swagger document in my small Nest.js app according to this documentation: https://docs.nestjs.com/recipes/swagger
How do I setup dto to correctly show schema in swagger? To be more specific, nested types. It shows only top level keys. If one of the keys is of type of something, it shows it just as empty object. Here is what I mean:
dto:
export class HealthCheckDataDto {
serverStatus: {} // dont have it typed yet;
dbStatus: MongoConnectionStateT;
}
swagger:
[
{
"serverStatus": {},
"dbStatus": {}
}
]
expected result in swagger example value:
[
{
"serverStatus": {},
"dbStatus": {
"isOnline": true,
"msg": "string"
}
}
]
This is the function:
@ApiResponse({ status: 200, description: 'blabla', type: [HealthCheckDataDto] })
@ApiResponse({ status: 500, description: 'blabla, but bad', type: [HealthCheckDataDto] })
@Get('/api/healthcheck')
healthCheckApp(@Res() res: Response<HealthCheckDataDto>) {
// check HCs and setup status code
const healthCheck: HealthCheckI = this.healthcheckService.getFullHealthCheck();
const statusCode = (healthCheck.dbStatus.isOnline) ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR;
// return that response
res.status(statusCode).json(healthCheck);
}
What I tried:
I'm doing something wrong, or missed something in documentation. Or maybe parser of that swagger module is unable to extract type/interface when generating json.
I missed one spot in NestJS Documentation: Generics and interfaces:
Since TypeScript does not store metadata about generics or interfaces, when you use them in your DTOs, SwaggerModule may not be able to properly generate model definitions at runtime.
Well, it makes sense.
In some specific scenarios (e.g. deeply nested arrays, matrices), you may want to describe your type by hand.
So, the final setup that works for me is following
Result<SomeDto>
Like this data are valid, swagger is properly generated. For additional swagger informations, use decorators directly in DTO.
You can show types in Swagger automatically using the OpenAPI CLI plugin.
Add:
"compilerOptions": {
"plugins": ["@nestjs/swagger"]
}
to nest-cli.json
, and add:
import { ApiProperty, ApiBody } from '@nestjs/swagger';
to each of your DTOs, and the plugin will automagically annotate and document your schemas!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With