What is the appropriate way to insert Timestamp value into Firestore database using DTOs and Entities?

147 Views Asked by At

I have a NestJS application in which I want to insert Task documents that have properties start_time and finish_time. I defined their types as Date in order to easily perform operations on them, but I want to store these dates as Timestamp (from firebase-admin/firestore) in my Firestore DB.

// using class-validator
export class CreateTaskDto {
  // ...
  @IsDate()
  @IsNotEmpty()
  start_time: Date;

  @IsDate()
  @IsOptional()
  finish_time: Date;
}

And from what I understand, my Task Entity should also have its dates defined as Date.

export class Task {
  // ...
  start_time: Date;
  finish_time?: Date;
}

From what I've read, the proper way to insert a new document into the DB is to transform data from the request using the DTO, and then setting up the Entity to be inserted with tasksCollection.add(Task).

The thing is, I'm also under the impression that the Task entity should have its typings as Date, as this is the way my application handles date transformations. This would imply that I can't simply set its start and finish dates as Timestamps before inserting it (if not, why use Typescript at all?)

I want to follow best practices and patterns, and before considering using an ORM I want to understand how to work around this issue, or if my impressions are wrong.

Should I change the way my DTO or Entity are defined? Are my assumptions wrong? What is the best way to handle this?

1

There are 1 best solutions below

1
Chanpols On

You have two options when utilising DTOs and entities to add a timestamp value to a Firestore database:

  • Create a procedure for converting the DTO into the Entity. The Date attributes in the DTO should be changed to Timestamp properties in the Entity using this way. After that, put a new document into the database using the modified Entity.

  • To handle your database entities, use a package like NestJS TypeORM. When inserting documents into Firestore, TypeORM can automatically convert Date values to Timestamp properties.

The best approach for you will depend on your specific needs and preferences. If you want to have complete control over how your data is stored and retrieved, then you may prefer the first approach. If you are looking for a simpler solution, then you may prefer the second approach.

References: