Search code examples
enumsswaggernestjs

How does Swagger document NestJS Reusable Enums?


Does anyone have an easy way to document reusable enums in nestjs using swagger? I don't mean showing them as options in a request. I am looking to document the enums themselves, since they are not very understandable on their own:

export enum ScanState {
  SCAN_WAITING_FOR_CAPTURE_DATA = 'SCAN_WAITING_FOR_CAPTURE_DATA',
  SCAN_VALIDATING_CAPTURE_DATA = 'SCAN_VALIDATING_CAPTURE_DATA',
  SCAN_CAPTURE_DATA_VALID = 'SCAN_CAPTURE_DATA_VALID',
  SCAN_CAPTURE_DATA_INVALID = 'SCAN_CAPTURE_DATA_INVALID',
}

I would think there would be some kind of @Schema or @ApiAdditionalProperty or something I could just add to the top of the enum for documentation, which would then be added to the Schemas portion of the Swagger docs similar to how it already works with classes. I'm using @nestjs/swagger version 6.0.4.

Seems to be a classic Swagger/NestJS problem, but I haven't been able to find a good solution elsewhere. Thank you, any help is greatly appreciated!


Solution

  • My ultimate solution was to create some description and property constants like this:

    export enum ScanState {
      SCAN_WAITING_FOR_INPUT = 'SCAN_WAITING_FOR_INPUT',
      SCAN_VALIDATING_INPUT = 'SCAN_VALIDATING_INPUT',
      SCAN_INPUT_VALID = 'SCAN_INPUT_VALID',
      SCAN_INPUT_INVALID = 'SCAN_INPUT_INVALID',
    }
    
    export const scanStates = Object.values(ScanState);
    
    export const scanStateDescription = `
    * \`${ScanState.SCAN_WAITING_FOR_INPUT}\`: description
    * \`${ScanState.SCAN_VALIDATING_INPUT}\`: description
    * \`${ScanState.SCAN_INPUT_VALID}\`: description
    * \`${ScanState.SCAN_INPUT_INVALID}\`: description
    `;
    
    export const scanStateApiProperty: ApiPropertyOptions = {
      enum: scanStates,
      example: ScanState.SCAN_INPUT_VALID,
      description: `The current state of the scan. The following states are possible: ${scanStateDescription}`,
    };
    

    Then, in the dto that is being documented, I add the property const to the field:

    @ApiProperty(scanStateApiProperty)
    state: ScanState;
    

    Which leads to the swagger docs looking like this:

    enter image description here

    Not my favorite solution, but it gets the job done! Hopefully this will help someone if they run into the same thing in the future :-)