Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nullish with id autoincrement #162

Open
vigyanhoon opened this issue Aug 17, 2023 · 4 comments
Open

nullish with id autoincrement #162

vigyanhoon opened this issue Aug 17, 2023 · 4 comments

Comments

@vigyanhoon
Copy link

Right now zod-prisma will generate zod file without nullish for ids that are auto incremented. We dont pass ids from client where its auto incremented, so it should be optional/nullish when generated.

May be you guys need following code fix in your types.ts

image
@ic-dominic
Copy link

Seconded, I've ran into this issue multiple times already.

I think by default the @default(autoincrement()) should make the zod object ID nullish and maybe an opt-out can be provided to the generator for people that don't want this behaviour.

@sterba-tech
Copy link

My solution

Currently I am solving this issue by re-exporting the generated model and omitting fields I do not want to have there.

import { OrderModel as OrderModelGenerated } from "db/zod"

export const OrderModel = OrderModelGenerated.omit({
  id: true,
  createdAt: true,
  updatedAt: true,
})

Suggestions

I think the best way how to solve would be adding excludeFields to the generator configuration.

generator zod {
  provider                 = "zod-prisma"
  excludeFields            = ["id", "createdAt", "updatedAt"]
  // ... other options
}

Another way could be manually add some zod-omit annotation above the field itself in Prisma schema.

Just starting with this problematic, might get to creating a PR later when I will know more pros and cons of possible solutions.

@vladaman
Copy link

We got the same issue. We use Zod + Prisma + tRPC + fastify, which requires the client to provide an id when creating a new record.

So far we've solved it with following:

export const connectorsRouter = router({
  create: authedProcedure.input(UserModel.omit({id: true, updatedAt: true, createAt: true}))
    .mutation(async (opts) => {
      let server = opts.ctx.req.server;
      return await server.prisma.user.create({
        data: {
          ...opts.input, id: DbHelpers.getRandomArbitrary(100_000_000, 900_000_000) // generates random number
        }
      })
    }),

@andrewmartin
Copy link

@vladaman thanks for your suggestion, this seems like a worthy solution! Would be really good to have some simple decorator option to make them nullish though. I'm going to +1 this thread :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants