omar-dulaimi / prisma-trpc-generator

Prisma 2+ generator to emit fully implemented tRPC routers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support date strings

omar-dulaimi opened this issue · comments

Problem

payload {
      data: {
        name: 'Blanca Hyatt',
        createdAt: 2022-08-09T03:58:40.668Z,
        updatedAt: 2022-08-08T18:58:18.021Z
      }
    }

result [
      {
        code: 'invalid_type',
        expected: 'date',
        received: 'string',
        path: [ 'data', 'createdAt' ],
        message: 'Expected date, received string'
      },
      {
        code: 'invalid_type',
        expected: 'date',
        received: 'string',
        path: [ 'data', 'updatedAt' ],
        message: 'Expected date, received string'
      }
    ]

Suggested solution

const dateSchema = z.preprocess((arg) => {
  if (typeof arg == "string" || arg instanceof Date) return new Date(arg);
}, z.date());
type DateSchema = z.infer<typeof dateSchema>;
// type DateSchema = Date

dateSchema.safeParse(new Date("1/12/22")); // success: true
dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true

Alternatives

new Date('2022-08-09T03:58:40.668Z');

Additional context

Taken from this issue: #22

it would be really cool if it was implemented 👍

hey, not sure this should be covered by prisma-trpc-generator. Instead it should be documented imo

create a file trpcOptions.ts

import superjson from "superjson";

const trpcOptions = {
  transformer: superjson,
}
export default trpcOptions;

import that file both inside your prisma.schema

generator trpc {
  provider          = "prisma-trpc-generator"
  output            = "./trpc"
  isGenerateSelect  = true
  isGenerateInclude = true
  withMiddleware    = false
  withShield        = true
  contextPath       = "../server/trpcContext"
  trpcOptionsPath   = "../server/trpcOptions"  <-- there
}

and inside your server's config, either createClient or createTRPCNext

export const api = createTRPCNext<AppRouter>({
  config() {
    return {
       ...trpcOptions,