15

First thing I came up with, is by calling computedInputs in the nexusPrisma option. But it won't work since they need to be handled differently depending on the situation, but globally:

1. create -> createdAt = now, updatedAt = null
2. update -> createdAt = keep as it is, updatedAt = now

In order to make it work, I need to set computedInputs individually like so:

t.crud.createOneX({
  computedInputs: {
    createdAt: () => DateTime.utc().toString(),
    updatedAt: () => null,
  },
});

t.crud.updateOneX({
  computedInputs: {
    createdAt: () => undefined,
    updatedAt: () => DateTime.utc().toString(),
  },
});

While this might work, I'm unable to "compute" these inputs on the nested models. In order to prevent passing createdAt/updatedAt, I have to create another t.crud on that resource as well, without these timestamps.

The last workaround for this that might work, is to not use t.crud at all, which is a bummer.

Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116

1 Answers1

77

Thank you for asking the question.

Prisma can handle the createdAt and updatedAt columns for you in your models. Add the @default(now()) and @updatedAt attributes to your createdAt and updatedAt columns respectively. You can add the columns to your models like this:

model Post {
  id               Int                @id @default(autoincrement())
  title            String
  content          String?
  published        Boolean?           @default(false)
  createdAt        DateTime           @default(now())
  updatedAt        DateTime           @updatedAt
}

You can learn more on the @default(now()) and @updatedAt in our docs.

In case you run into any other issues and queries, I'll be happy to help

ConcurrentHashMap
  • 4,998
  • 7
  • 44
  • 53
Alex Ruheni
  • 989
  • 5
  • 6
  • 1
    I eventually ended up manually creating these fields. Felt more in control . PS - If you have just signed up in order to answer my question, then I just want to let you know that you're a legend. – Eliya Cohen Dec 28 '20 at 17:25
  • 1
    When using `@default(now())` and `@updatedAt` set 2 differents timestamp when created, determine if a record have been updated using `createdAt !== updatedAt` always returns `true`. – TryingToImprove Nov 02 '21 at 13:44
  • 1
    Be aware that subsequently adding `createdAt` with `@default(now())` adds the current date. This may lead to wrong intepretation of the creation date later down the line. – alexanderdavide Jun 24 '22 at 11:51