Adding custom model validations in a model created using Prisma ORM, Resulting in weird behaviour

39 views Asked by At

Consider this Scenario. I have this scenario, (I'm using zod prisma types ref: here to add validations.

my prisma.schema setup for the models:


/// @zod.import(["import { projectNumberValidator } from "../validation-helpers/project-number-validator";"]).refine(async (data) => { return await projectNumberValidator(data)}, { message: 'projectNumber is not valid' })
model Account{
  id                         String               @id @default(cuid())
  ProjectAccountNumber       String
  project                    Project              @relation(fields: [projectId], references: [id])
  projectId                  Int
}

model Project{
    id     String
    name   String
    projectRules ProjectRules[]
}


model ProjectRules{
  id         String
  rule       String    // This is the regex containing the project rule
  project    Project   @relation(fields: [projectId], references: [id])
  projectId  Int
}

I had Setup a custom model validation in this schema such that during the account creation, so that the projectAccountNumber is matching its corresponding project rules. (we have to query for the project rules using the project id and pass the validation if it matches with any resulting regex pattens). I'm running into a few issues while testing this. when I tried to parse my input data, using the generated schema type similar to the one that is mentioned here. I'm experiencing this error

 {
    "code": "invalid_type",
    "expected": "string",
    "received": "undefined",
    "path": [
      "id"
    ],
    "message": "Required"
  }

Now to some extent I understand this, this is happening because the id is a required field in my model.

export const UtilityAccountSchema = z.object({
  id: z.string().cuid(),
  projectAccountNumber: z.string(),
  projectId: z.number().int()
})

what I don't understand is id should be auto-generated. so I'm a bit clueless on what could be done here.

0

There are 0 answers