'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?



Solution 1:[1]

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

Solution 2:[2]

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'){}

Solution 3:[3]

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, ...}),
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jay McDoniel
Solution 2 Alwin07
Solution 3 Sopheak Sek