I'm trying to set a database field to the current timestamp. While Prisma Schema Reference does allow the ability to set a field to the current time using now(), the Prisma API does not seem to support the function.
Is there a way I can set a field to the current database date and time without using $executeRaw?
I'm currently using a $queryRaw to get the current DB timestamp like this:
this.user = await prisma.User.create({
data: {
username: username,
email: email,
emailVerified: await prisma.$queryRaw `SELECT NOW()`,
},
});
While this serves its purpose, it has two problems:
I've also looked at this question, but...
...
emailVerified = new Date
...
would get the timestamp at the client, but I want to ensure that the variable has the server timestamp.
Any pointers will be super helpful.
now()
returns the timestamp from the server, not from the client, since Prisma is a server-side only library.
https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#now
The value of emailVerified
will depend on where you generate its value before passing it to Prisma. If you are generating the value of emailVerified
in a browser, then the value will always be using whatever time the browser thinks it is. If you generate the value in the server, then the time will always be the server time (ignoring the scenario of having servers in multiple geographic regions.) However you're telling the frontend to run this backend operation (REST endpoint, GraphQL mutation, etc.) you can probably add some sort of flag shouldSetEmailVerifiedTime
to instruct the backend to set the time to the current time as it exists on the backend.
Username/password:
this.user = await prisma.User.create({
data: {
username: username,
email: email,
},
});
// Later...
this.user = await prisma.User.update({
data: {
emailVerified: {
set: new Date()
}
},
where: {
id: "ID_HERE"
}
});
Social login code:
this.user = await prisma.User.create({
data: {
username: username,
email: email,
emailVerified: new Date()
},
});