3

I'm using @Schema({ timestamps: true }) to add createdAt & updatedAt to my records and returning these with the response. But seems the OpenAPI spec getting generated by the NestJs's Swagger plugin is not adding the createdAt or updatedAt. How can I get these two added to the generated OpenAPI spec.

openapi: 3.0.0
paths:
  /participants/{participantId}:
    get:
      operationId: ParticipantController_findOne
      parameters:
        - name: participantId
          required: true
          in: path
          schema:
            type: string
      responses:
        '200':
          description: The participant
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Participant'
components:
  schemas:
    Participant:
      type: object
      properties:
        name:
          type: string
        description:
          type: string
        participantId:
          type: string
      required:
        - name
        - description
        - participantId

My controller looks like this

@ApiOkResponse({
  description: 'Get a participant',
  type: Participant,
})
@Get(':participantId')
findOne(
  @Param('participantId') participantId: string,
): Promise <Participant> {
  return this.participantService.findOne(participantId);
}

My Mongoose schema looks like this,

@Schema({ timestamps: true })
export class Participant {
  @Prop()
  @ApiProperty()
  participantId: string;

  @Prop()
  @ApiProperty()
  name: string;

  @Prop()
  @ApiProperty()
  description: string;
}
export const ParticipantSchema = SchemaFactory.createForClass(Participant);

My response looks like this,

{
    "name": "Participant One",
    "description": "The particicpant one",
    "participantId": "participant-001",
    "createdAt": "2022-10-14T20:00:52.778Z", // Added automatically by the `timestamps: true`
    "updatedAt": "2022-10-14T20:04:31.081Z",// Added automatically by the `timestamps: true`
}
Milindu Sanoj Kumarage
  • 2,714
  • 2
  • 31
  • 54

1 Answers1

0

You can add createdAt and updatedAt to schema without @Prop()

@Schema({ timestamps: true })
export class Participant {
  @Prop()
  @ApiProperty()
  participantId: string;

  @Prop()
  @ApiProperty()
  name: string;

  @Prop()
  @ApiProperty()
  description: string;

  @ApiProperty()
  createdAt: Date;

  @ApiProperty()
  updatedAt: Date;
}
export const ParticipantSchema = SchemaFactory.createForClass(Participant);