Reza
Reza

Reputation: 19843

NestJs Swagger: How to define Api Property for dynamic classes

I have below class

export class DocumentsSteps {
    @ApiProperty({type: ???})
    [type: string]: DocumentStep;
}

How should I define ApiProperty type?

Upvotes: 8

Views: 5585

Answers (4)

Ashu Sahu
Ashu Sahu

Reputation: 601

I found a solution for this, it looks a little ugly on swagger but it's the best possible way.

Using additionalProperties, you can add dynamic keys, with a typed value by providing a reference to your Dto. The Dto will not be a part of some other response and may not be available in swagger, to expose it, we need to use @ApiExtaModels()


@ApiExtraModels(DocumentStep)
export class DocumentsSteps {
    @ApiProperty({
        additionalProperties: { oneOf: [{ $ref: getSchemaPath(DocumentStep) }] },
    })
    [type: string]: DocumentStep;
}

The result looks like this enter image description here

Upvotes: 1

Alwin
Alwin

Reputation: 1057

You can wrap it with a function

export type Constructor<I> = new (...args: any[]) => I

function ErrorDto(statusCode: number, message: string): Constructor<Error>{
  class Error implements Error{
    @ApiProperty({ example: statusCode })
    readonly statusCode: number

    @ApiProperty({ example: message })
    readonly message: string

  }
  return Error
}
export class UnauthorizedErrorDto extends ErrorDto(401, 'Unauthorized'){}
export class BadRequestErrorDto extends ErrorDto(400, 'Bad Request'){}

Upvotes: 3

Jay McDoniel
Jay McDoniel

Reputation: 70111

As of right now (9/21/2021), this isn't possible with Nest's @nestjs/swagger library, due to the fact that there's no field to reflect metadata on. There may be an opportunity to open a pull request to allow for the use of dictionaries with the library, but right now your best bet would be modifying the swagger document that Nest generates and adding it on your own at the moment

Upvotes: 3

Sopheak Sek
Sopheak Sek

Reputation: 162

Check this out

https://docs.nestjs.com/custom-decorators#decorator-composition

You could implement another decorator to extends the ApiProperty

export function CustomApiProperty(type: string) {
  return applyDecorators(
    ApiProperty({type, ...}),
  );
}

Upvotes: -1

Related Questions