risen228 / nestjs-zod-prisma

Zod Prisma fork for nestjs-zod
MIT License
62 stars 11 forks source link

[feature request]: support reading `db.VarChar` and limit string length in zod via `.minLength().maxLength()` #16

Closed Innei closed 1 year ago

Innei commented 1 year ago

Hi, I usually define model schema like this.

model Post {
  id       String    @id @default("")
  slug     String    @unique @db.VarChar(80)
  text     String
  title    String    @db.VarChar(255)
  created  DateTime  @default(now()) @map("created_at")
  modified DateTime? @updatedAt @map("updated_at")

  @@index([slug])
  @@index([created])
}

I use @db.VarChar(80) to define slug as a length-limited string. So if the generated schema is like this, it should be so cool.

export const PostModel = z.object({
  id: z.string(),
  slug: z.string().minLength(0).maxLength(80),
  text: z.string(),
  title: z.string(),
  created: z.date(),
  modified: z.date().nullish(),
})

Thank you for your support

fbudimir commented 1 year ago

If you're still struggling with this, I've found a way and it is to use comments in your schema file like this: (this is from zod's docs)

generator zod {
  provider       = "zod-prisma-types"
  output         = "./zod"
}

/// @zod.import(["import { myFunction } from 'mypackage';"])
model MyPrismaScalarsType {
  /// @zod.string({ invalid_type_error: "some error with special chars: some + -*#'substring[]*#!§$%&/{}[]", required_error: "some other", description: "some description" }).cuid()
  id         String    @id @default(cuid())
  /// Some comment about string @zod.string.min(3, { message: "min error" }).max(10, { message: "max error" })
  string     String?
  /// @zod.custom.use(z.string().refine((val) => validator.isBIC(val), { message: 'BIC is not valid' }))
  bic        String?
  /// @zod.number.lt(10, { message: "lt error" }).gt(5, { message: "gt error" })
  float      Float
  floatOpt   Float?
  /// @zod.number.int({ message: "error" }).gt(5, { message: "gt error" })
  int        Int
  intOpt     Int?
  decimal    Decimal
  decimalOpt Decimal?
  date       DateTime  @default(now())
  dateOpt    DateTime? /// @zod.date({ invalid_type_error: "wrong date type" })  bigInt     BigInt /// @zod.bigint({ invalid_type_error: "error" })
  bigIntOpt  BigInt?
  /// @zod.custom.use(z.lazy(() => InputJsonValue).refine((val) => myFunction(val), { message: 'Is not valid' }))
  json       Json
  jsonOpt    Json?
  bytes      Bytes /// @zod.custom.use(z.instanceof(Buffer).refine((val) => val ? true : false, { message: 'Value is not valid' }))
  bytesOpt   Bytes?
  /// @zod.custom.use(z.string().refine((val) => myFunction(val), { message: 'Is not valid' }))
  custom     String?
  exclude    String? /// @zod.custom.omit(["model", "input"])

  updatedAt DateTime @updatedAt
}
Innei commented 1 year ago

Thank you!