graphql-nexus / nexus

Code-First, Type-Safe, GraphQL Schema Construction
https://nexusjs.org
MIT License
3.4k stars 275 forks source link

How can I save DateTime objects using nexus? #1173

Open SecretariatV opened 6 months ago

SecretariatV commented 6 months ago

Hi. I made server using Prisma, GraphQL, Nexus and MongoDB. I would like save datetime object to DB. So, I declared DateTime using graphql-scalars and nexus.

export const DateTime = asNexusMethod(DateTimeResolver, "date");

const Mutation = objectType({
  name: "Mutation",
  definition(t) {
    t.field("create", {
      type: "Table",
      args: {
        point: nonNull(floatArg()),
        status: nonNull(intArg()),
        startedAt: nonNull("DateTime"),
      },
      resolve: async (_, args, context: Context) => {
        return context.prisma.crash.create({
          data: {
            point: args.point,
            status: args.status,
            startedAt: args.startedAt,
          },
        });
      },
    });
  },
});

const Table= objectType({
  name: "Table",
  definition(t) {
    t.nonNull.string("id");
    t.nonNull.float("point");
    t.int("status");
    t.nonNull.field("created", { type: "DateTime" });
    t.nonNull.field("startedAt", { type: "DateTime" });
  },
});

const schemaWithoutPermissions = makeSchema({
  types: [Table, Query, Mutation, DateTime],
  outputs: {
    schema: __dirname + "/../schema.graphql",
    typegen: __dirname + "/generated/nexus.ts",
  },
});

Query

{  
  "point": 33.22,
  "status": 1,
  "startedAt": 2024-12-03T10:15:30Z
}

However, if I try to save StartedAt, an error occurs.

{
  "errors": [
    {
      "message": "Variable \"$startedAt\" of non-null type \"DateTime!\" must not be null.",
      "locations": [
        {
          "line": 1,
          "column": 101
        }
      ]
    }
  ]
}

What is the solution?