How is DateTime automatically handled when saving and reading from a database #1345
-
Context: I am building a backend application. This is what my stack looks like:
Disclaimer: I am not very familiar with the inner workings of JS/TS. I have a working knowledge of the languauge(s). I currently use this library called pg-promise to connect to my PostgreSQL instance for querying my database. I noticed something interesting when I save and load This is the SQL statement I used to create the database: CREATE TABLE "PROJECT_TEMPLATES" (
"id" UUID,
"name" TEXT NOT NULL,
"url" TEXT NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL,
"updated_at" TIMESTAMPTZ NOT NULL,
PRIMARY KEY ("id")
); And the code snippet I use to save and query this table: saveProjectTemplate = (project) => {
const query = `INSERT INTO "PROJECT_TEMPLATES" AS pt
("id", "name", "url", "created_at", "updated_at")
VALUES
($(id), $(name), $(url), $(timestamps.createdAt), $(timestamps.updatedAt))
ON CONFLICT ("id") DO UPDATE
SET "name" = $(name), "url" = $(url), "updated_at" = $(timestamps.updatedAt)
WHERE pt."id" = $(id)`;
return obj.none(query, project);
}
findProjectTemplate = (id) => {
const query = `SELECT * FROM "PROJECT_TEMPLATES"
WHERE "id" = $1`;
return obj.oneOrNone(query, [id]);
} Here, class ProjectTemplate {
public readonly id: string
public readonly name: string
public readonly url: string
public readonly timestamps: Timestamps
constructor(id: string, name: string, url: string, timestamps: Timestamps) {
this.id = id
this.name = name
this.url = url
this.timestamps = timestamps
}
}
class Timestamps {
public readonly createdAt: DateTime
public readonly updatedAt: DateTime
constructor(createdAt: DateTime, updatedAt: DateTime) {
this.createdAt = createdAt
this.updatedAt = updatedAt
}
} And the query returns a type of interface ProjectTemplateRecord {
id: string
name: string
url: string
created_at: DateTime
updated_at: DateTime
} I noticed that the Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
The What's more surprising is the |
Beta Was this translation helpful? Give feedback.
-
Answer in this comment: #1345 (reply in thread) |
Beta Was this translation helpful? Give feedback.
Answer in this comment: #1345 (reply in thread)