flightcontrolhq / superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
https://www.flightcontrol.dev?ref=superjson
MIT License
4.13k stars 91 forks source link

Struggling with Dates #241

Closed woodman231 closed 1 year ago

woodman231 commented 1 year ago

This may not be a bug with this package specifically, but I am having a hard time with dates. Just doing an example application right now for "Todos", I am using the entire T3 stack with with trpc and superjson as a transformer.

For the moment I am using MS SQL and Prisma. I am using a Prisma type of DateTime, but using @db.Date in my definition. My Zod validators are using the z.Date().nullable in the correct places.

When I create a TODO the date shows correctly, and shows correctly in the database, but when I receive the date, it has been localized. For now I am running the client and the server on the same machine. So I am not sure what I am doing wrong.

Here are a few snippets of code and screen shots.

const t = initTRPC.context<typeof createTRPCContext>().create({
  transformer: superjson,
  errorFormatter({ shape, error }) {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError:
          error.cause instanceof ZodError ? error.cause.flatten() : null,
      },
    };
  },
});

part of schema.prisma

model Todo {
  id       String    @id @default(cuid())
  userId   String
  title    String
  dueDate  DateTime? @db.Date
  complete Boolean
  user     User      @relation(fields: [userId], references: [id], onDelete: Cascade)
}

How I am creating my models. This is the createTodoRequest.ts file

import { z } from "zod";

export const createTodoRequestValidator = z.object({
    title: z.string().min(1),
    dueDate: z.date().nullable(),
    complete: z.boolean(),
});

export type CreateTodoRequest = z.infer<typeof createTodoRequestValidator>;

The route handler is then defined as such

export const createRouteHandler = protectedProcedure.input(createTodoRequestValidator).mutation(async ({ ctx, input }) => {
    const userId = ctx.session.user.id;

    const dataToInsert = {
        userId: userId,
        title: input.title,
        dueDate: input.dueDate,
        complete: input.complete
    }

    const results = await ctx.prisma.todo.create({ data: dataToInsert })

    return results;
})

Then I use the models with my react-hook-form ...

import { type CreateTodoRequest, createTodoRequestValidator } from "../routeHandlerModels/createTodoRequest";
import { type SubmitErrorHandler, type SubmitHandler, useForm } from "react-hook-form";

const CreateTodoPage: NextPage = () => {
    const { mutate, isLoading, isSuccess } = api.todos.create.useMutation();
    const router = useRouter();

    const { formState, handleSubmit, register } = useForm<CreateTodoRequest>({
        resolver: zodResolver(createTodoRequestValidator),
        values: {
            title: "",
            complete: false,
            dueDate: null
        }
    })

   // Rest of the handlers, and UI..

}

When the record is created in the database it is what I would expect. image

However, when I use my query to retrieve the data it comes back like this

image

This is how I define my getAllRoute and here is a screen shot of what it looks like for that console.log before it is sent to the client (before superjson get's it).

export const getAllRouteHandler = protectedProcedure.query(async ({ctx}) => {
    const userId = ctx.session.user.id;
    const results = await ctx.prisma.todo.findMany({where: { userId: userId }})

    if(results) {
      const firstResult = results[0];
      if(firstResult) {
        const firstResultDueDate = firstResult.dueDate;
        console.log(firstResultDueDate);
        if(firstResultDueDate) {
          console.log(firstResultDueDate.toISOString());
        }
      }
    }

    return results;
});

image

Any suggestions on what I can do?

If it helps. This is also the full server side entry for my trpc

/**
 * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS:
 * 1. You want to modify request context (see Part 1).
 * 2. You want to create a new middleware or type of procedure (see Part 3).
 *
 * TL;DR - This is where all the tRPC server stuff is created and plugged in. The pieces you will
 * need to use are documented accordingly near the end.
 */

import { initTRPC, TRPCError } from "@trpc/server";
import { type CreateNextContextOptions } from "@trpc/server/adapters/next";
import { type Session } from "next-auth";
import superjson from "superjson";
import { ZodError } from "zod";
import { getServerAuthSession } from "~/server/auth";
import { prisma } from "~/server/db";

/**
 * 1. CONTEXT
 *
 * This section defines the "contexts" that are available in the backend API.
 *
 * These allow you to access things when processing a request, like the database, the session, etc.
 */

type CreateContextOptions = {
  session: Session | null;
};

/**
 * This helper generates the "internals" for a tRPC context. If you need to use it, you can export
 * it from here.
 *
 * Examples of things you may need it for:
 * - testing, so we don't have to mock Next.js' req/res
 * - tRPC's `createSSGHelpers`, where we don't have req/res
 *
 * @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts
 */
const createInnerTRPCContext = (opts: CreateContextOptions) => {
  return {
    session: opts.session,
    prisma,
  };
};

/**
 * This is the actual context you will use in your router. It will be used to process every request
 * that goes through your tRPC endpoint.
 *
 * @see https://trpc.io/docs/context
 */
export const createTRPCContext = async (opts: CreateNextContextOptions) => {
  const { req, res } = opts;

  // Get the session from the server using the getServerSession wrapper function
  const session = await getServerAuthSession({ req, res });

  return createInnerTRPCContext({
    session,
  });
};

/**
 * 2. INITIALIZATION
 *
 * This is where the tRPC API is initialized, connecting the context and transformer. We also parse
 * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation
 * errors on the backend.
 */

const t = initTRPC.context<typeof createTRPCContext>().create({
  transformer: superjson,
  errorFormatter({ shape, error }) {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError:
          error.cause instanceof ZodError ? error.cause.flatten() : null,
      },
    };
  },
});

/**
 * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)
 *
 * These are the pieces you use to build your tRPC API. You should import these a lot in the
 * "/src/server/api/routers" directory.
 */

/**
 * This is how you create new routers and sub-routers in your tRPC API.
 *
 * @see https://trpc.io/docs/router
 */
export const createTRPCRouter = t.router;

/**
 * Public (unauthenticated) procedure
 *
 * This is the base piece you use to build new queries and mutations on your tRPC API. It does not
 * guarantee that a user querying is authorized, but you can still access user session data if they
 * are logged in.
 */
export const publicProcedure = t.procedure;

/** Reusable middleware that enforces users are logged in before running the procedure. */
const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
  if (!ctx.session || !ctx.session.user) {
    throw new TRPCError({ code: "UNAUTHORIZED" });
  }
  return next({
    ctx: {
      // infers the `session` as non-nullable
      session: { ...ctx.session, user: ctx.session.user },
    },
  });
});

/**
 * Protected (authenticated) procedure
 *
 * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies
 * the session is valid and guarantees `ctx.session.user` is not null.
 *
 * @see https://trpc.io/docs/procedures
 */
export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);

And this is my entry point for the client of trpc

/**
 * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which
 * contains the Next.js App-wrapper, as well as your type-safe React Query hooks.
 *
 * We also create a few inference helpers for input and output types.
 */
import { httpBatchLink, loggerLink } from "@trpc/client";
import { createTRPCNext } from "@trpc/next";
import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
import superjson from "superjson";
import { type AppRouter } from "~/server/api/root";

const getBaseUrl = () => {
  if (typeof window !== "undefined") return ""; // browser should use relative url
  if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url
  return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost
};

/** A set of type-safe react-query hooks for your tRPC API. */
export const api = createTRPCNext<AppRouter>({
  config() {
    return {
      /**
       * Transformer used for data de-serialization from the server.
       *
       * @see https://trpc.io/docs/data-transformers
       */
      transformer: superjson,

      /**
       * Links used to determine request flow from client to server.
       *
       * @see https://trpc.io/docs/links
       */
      links: [
        loggerLink({
          enabled: (opts) =>
            process.env.NODE_ENV === "development" ||
            (opts.direction === "down" && opts.result instanceof Error),
        }),
        httpBatchLink({
          url: `${getBaseUrl()}/api/trpc`,
        }),
      ],
    };
  },
  /**
   * Whether tRPC should await queries when server rendering pages.
   *
   * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false
   */
  ssr: false,
});

/**
 * Inference helper for inputs.
 *
 * @example type HelloInput = RouterInputs['example']['hello']
 */
export type RouterInputs = inferRouterInputs<AppRouter>;

/**
 * Inference helper for outputs.
 *
 * @example type HelloOutput = RouterOutputs['example']['hello']
 */
export type RouterOutputs = inferRouterOutputs<AppRouter>;
Skn0tt commented 1 year ago

Hi @woodman231! I agree this is not related to SuperJSON. To me, it looks like this is something with a timezone difference between your browser and server. Maybe this post could help you understand what's going on: https://www.ursahealth.com/new-insights/dates-and-timezones-in-javascript