DEV Community

mark vachi
mark vachi

Posted on

Handling Multiple Schemas in NestJS Swagger with @ApiProperty ๐Ÿš€

Swagger simplifies API documentation, but handling multiple schemas can be challenging. In NestJS, you can use the @ApiProperty decorator to tackle this. Let's explore this in a scenario. ๐Ÿง

The Scenario ๐Ÿ“œ

Imagine building an e-commerce platform with NestJS. You have an endpoint to update orders, which can contain an array of products. These products can be newly created or updated, requiring two schemas. ๐Ÿ›’๐Ÿ“ฆ

Defining Product Schemas ๐Ÿ“

Start by defining product schemas. You have a Product class with id, name, and quantity. Create two DTOs: CreateProductDto and UpdateProductDto for product creation and updates. ๐Ÿ“‹๐Ÿ›๏ธ

class Product {
  // Properties
}

class CreateProductDto extends OmitType(Product, ['id'] as const) {}
class UpdateProductDto extends Product {}
Enter fullscreen mode Exit fullscreen mode

Handling Multiple Schemas ๐Ÿคฏ

Now, let's handle multiple schemas within the UpdateOrderRequestDto, representing an order update request. This DTO includes an array of products, which can be of either CreateProductDto or UpdateProductDto. ๐Ÿ”„๐Ÿ“‘

@ApiExtraModels(CreateProductDto, UpdateProductDto)
class UpdateOrderRequestDto {
  // Properties

  @ApiProperty({
    type: 'array',
    oneOf: [
      { $ref: getSchemaPath(CreateProductDto) },
      { $ref: getSchemaPath(UpdateProductDto) },
    ],
  })
  @Transform(({ value }) => {
    // Transformation logic
  })
  products: (CreateProductDto | UpdateProductDto)[];
}
Enter fullscreen mode Exit fullscreen mode

Here's the breakdown:

  • Use @ApiExtraModels to include CreateProductDto and UpdateProductDto in Swagger documentation. ๐Ÿ“šโœจ
  • In UpdateOrderRequestDto, use @ApiProperty to define an array with a choice between CreateProductDtoand UpdateProductDto using oneOf. ๐Ÿ“Š๐Ÿงฉ
  • Utilize @Transform to conditionally transform data based on the id property for creation or update. ๐Ÿ”„๐Ÿ”€

Conclusion ๐ŸŽ‰

Handling multiple schemas in NestJS Swagger enhances API documentation for complex data structures. By leveraging @ApiProperty, you can clearly define schemas, making your API documentation precise and comprehensible. ๐Ÿ“–๐Ÿš€

This approach simplifies API development with Swagger, resulting in well-documented and robust APIs. Mastering Swagger's features is key to creating efficient APIs that streamline your development workflow. ๐Ÿ› ๏ธ๐Ÿ‘จโ€๐Ÿ’ป

Top comments (0)