NestJs Swagger: How to define Api Property for dynamic classes
Asked Answered
C

4

8

I have below class

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

How should I define ApiProperty type?

Capsule answered 21/9, 2021 at 5:13 Comment(0)
A
2

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

Agathaagathe answered 21/9, 2021 at 17:19 Comment(1)
would you please add a small sample here about the changes manually, what should it look likeCapsule
T
3

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'){}
Truism answered 9/12, 2021 at 18:25 Comment(0)
A
2

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

Agathaagathe answered 21/9, 2021 at 17:19 Comment(1)
would you please add a small sample here about the changes manually, what should it look likeCapsule
I
1

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

Isolda answered 9/9, 2023 at 12:34 Comment(0)
L
-1

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, ...}),
  );
}
Lend answered 21/9, 2021 at 5:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.