I have an app where I define the API response schemas as plain javascript objects according to the open-api spec. Currently I am passing that to the ApiResponse
decorator in @nestjs/swagger as follows:
class CatsController {
@Get()
@ApiResponse({
status: 200,
schema: catSchema // plain js object imported from another file
})
getAll() {}
}
This is working great. However, the output open-api spec contains the verbose schema for every endpoint which uses the catSchema
. Instead, I want the output swagger file to have the catSchema under the components
section, and have a corresponding $ref
in the paths section.
components:
schemas:
Cat:
properties:
name:
type: string
paths:
/cats/{id}:
get:
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/Cat'
So far, it seems the only way to do that would be to define the schema as a DTO class and use the ApiProperty
decorator for each class property. In my case, that means I have to refactor all the plain object schemas in open-api spec to be DTO classes.
Is there a way to feed the raw schema to the library and get the expected outcome?
// instead of this:
class CatDto {
@ApiProperty()
name: string;
}
// I want to do:
const catSchema = {
type: 'object',
properties: {
name: { type: 'string' }
}
}
@ApiProperty
is the tag by which swagger in NestJs understands the schema and it is not supported in inline schema design. Can you explain a bit more in detail on how do you want to pass the schema? – Ragged@ApiResponse
directly. It works well, except it doesn't do$ref
schemas. The output contains the schema directly under the responses section. Does that make sense? – Counteraccusation