swaggernestjsclass-transformernestjs-swagger

Optional Boolean Query Parameter Not Showing Up In Swagger


I'm using Nest.js with Swagger and the Swagger CLI enabled. I have an endpoint in a controller which has an optional boolean query parameter: includeAll that defaults to false. The endpoint looks like:

  @Get()
  findAll(
    @Query('includeArtifacts', ParseOptionalBool)
    includeArtifacts = false,
  ) {
    return this.toursService.findAll({ includeArtifacts });
  }

I'm using an Injectable Pipe Transform similar to what is described in the docs to parse the optional boolean value seen here:

export const toBoolean = (value?: string): boolean => {
  value = value?.toLowerCase();

  return value === 'true' || value === '1';
};

@Injectable()
export class ParseOptionalBool implements PipeTransform {
  transform(value?: any, metadata?: ArgumentMetadata): any {
    return toBoolean(value);
  }
}

Everything functions successfully; however, as seen below when I view the endpoint in Swagger there is no mention of my includeArtifacts endpoint.

Image of swagger docs with no parameter data


Solution

  • you can create simple class like this below:

    export class ParseOptionalBool {
      @ApiPropertyOptional()
      @IsBooleanString()
      @IsOptional()
      includeArtifacts: boolean;
    }
    

    and your controller will be like this:

     @Get()
      findAll(
        @Query() dto: ParseOptionalBool;
      ) {
        return this.toursService.findAll(dto);
      }
    

    but this will return object with string type, not boolean type, if you want to parse boolean type, you should do like this below:

    
      @ApiPropertyOptional()
      @IsBoolean()
      @IsOptional()
      @Transform(({ obj }) => obj.includeArtifacts == 'true')
      includeArtifacts: boolean;