srhuevo
srhuevo

Reputation: 420

NestJs Swagger body array with mixed types

I have created an endpoint to create bouchers but they can be created with any feature and each feature has a diferent type.

Example:

POST /code
{
  "code": "<String>"
  "features": [{
    "type": "expiredDate",
    "expiredDate": "<ISODate>"
  }, {
    "type": "referrer",
    "refererId": "<UUID>"
  }]
}

But it could also be used like this:

    POST /code
    {
      "code": "<String>"
      "features": [{
        "type": "referrer",
        "refererId": "<UUID>"
      }]
    }

or

    POST /code
    {
      "code": "<String>"
      "features": [{
        "type": "motivated-purchase",
        "pursache": "<UUID>"
      }]
    }

or... many similars things you know

How can I especify it in nestjs for swagger? I tried with anyOf but I can't get it

If someone knows how to do it with the openapi nomenclature, it could also help me

Upvotes: 2

Views: 3932

Answers (1)

srhuevo
srhuevo

Reputation: 420

I answer myself...

First you should create the diferents features DTO

export default class ExpiredDateFeatureDto {
    @ApiProperty({ type: String, required: true, enum: ['expiredDate'] })
    readonly type: string;

    @ApiProperty({ type: String, required: true })
    readonly expiredDate: string;
}

export default class ReferrerFeatureDto {
    @ApiProperty({ type: String, required: true, enum: ['referrer'] })
    readonly type: string;

    @ApiProperty({ type: String, required: true })
    readonly refererId: string;
}

export default class ExpiredDateFeatureDto {
    @ApiProperty({ type: String, required: true, enum: ['motivated-purchase'] })
    readonly type: string;

    @ApiProperty({ type: String, required: true })
    readonly pursache: string;
}

And add it in the main dto

@ApiExtraModels(ExpiredDateFeatureDto, ReferrerFeatureDto, ExpiredDateFeatureDto)
export default class CouponDto {
    @ApiProperty()
    readonly code: string;

    @ApiProperty({
        type: 'array',
        items: {
            oneOf: [{
                $ref: getSchemaPath(ExpiredDateFeatureDto) 
            }, {
                $ref: getSchemaPath(ReferrerFeatureDto) 
            }, {
                $ref: getSchemaPath(ExpiredDateFeatureDto) 
            }],
        },
    })
    @IsOptional()
    readonly features: FeatureDto[];
}

It is very important to add the annotation @ApiExtraModels in the main dto

Upvotes: 5

Related Questions