next.jsgraphqlprismaprisma-graphql

How to define createdAt and updatedAt in nexus for GraphQL?


I am currently working on GraphQL API in Next.js project w/ TypeScript. I was following this tutorial Prisma blog. However, I am not sure how to define the createdAt and updatedAt attributes. They are defined with DateTime type in the prisma schema. I am using MongoDB for the database.

  createdAt   DateTime      @default(now()) @map(name: "created_at")
  updatedAt   DateTime      @updatedAt @map(name: "updated_at")

Defining the type as string as string in the nexus schema is giving type errors.

t.nonNull.string('createdAt');
Types of property 'createdAt' are incompatible.
    Type 'Date' is not assignable to type 'string'.

Whereas, defining it as int throws error Int cannot represent non 32-bit signed integer value: 1661894591365

t.nonNull.int('createdAt');

What should be the data type for createdAt and updatedAt in order to make it type safe?


Solution

  • You might need to define a custom GraphQL Scalar when working with DateTime values. I would recommend using the graphql-scalars library and using the DateTime scalar. (It's also useful for other custom GraphQL scalars)

    The values for the DateTime fields are based on the ISO 8601 standard when working with Prisma. (Prisma schema reference).

    Here's also a snippet from graphql-scalar's docs on result coercion.

    JavaScript Date instances and timestamps (represented as 32-bit signed integers) are coerced to RFC 3339 compliant date-time strings. Invalid Date instances raise a field error.

    Here's some example usage:

    import { DateTimeResolver } from 'graphql-scalars'
    
    const DateTime = asNexusMethod(DateTimeResolver, 'date')
    
    t.nonNull.field('createdAt', { type: 'DateTime' })
    
    export const schema = makeSchema({
      types: [
        DateTime,
        /** Queries, mutations, and other scalar types here */
      ],
      /** more config options here */
    })