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

Added a config option to switch between nullable and nullish zod types. #173

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions .vscode/settings.json

This file was deleted.

Binary file added bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const configSchema = z.object({
useDecimalJs: configBoolean.default('false'),
imports: z.string().optional(),
prismaJsonNullability: configBoolean.default('true'),
useNullish: configBoolean.default('true'),
})

export type Config = z.infer<typeof configSchema>
Expand Down
13 changes: 10 additions & 3 deletions src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,13 @@ export const generateSchemaForModel = (
.forEach((field) => {
writeArray(writer, getJSDocs(field.documentation))
writer
.write(`${field.name}: ${getZodConstructor(field)}`)
.write(
`${field.name}: ${getZodConstructor(
field,
undefined,
config
)}`
)
.write(',')
.newLine()
})
Expand Down Expand Up @@ -212,7 +218,8 @@ export const generateRelatedSchemaForModel = (
.write(
`${field.name}: ${getZodConstructor(
field,
relatedModelName
relatedModelName,
config
)}`
)
.write(',')
Expand Down Expand Up @@ -242,7 +249,7 @@ export const populateModelFile = (
export const generateBarrelFile = (models: DMMF.Model[], indexFile: SourceFile) => {
models.forEach((model) =>
indexFile.addExportDeclaration({
moduleSpecifier: `./${model.name.toLowerCase()}`,
moduleSpecifier: `./${model.name.toLowerCase()}.js`,
})
)
}
1 change: 1 addition & 0 deletions src/test/functional/driver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ describe('Functional Tests', () => {
test.concurrent('Relation - 1 to 1', ftForDir('relation-1to1'))
test.concurrent('Imports', ftForDir('imports'))
test.concurrent('JSON', ftForDir('json'))
test.concurrent('Nullable fields', ftForDir('nullable'))
test.concurrent('Optional fields', ftForDir('optional'))
test.concurrent('Config Import', ftForDir('config-import'))

Expand Down
2 changes: 2 additions & 0 deletions src/test/functional/nullable/expected/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./user"
export * from "./post"
20 changes: 20 additions & 0 deletions src/test/functional/nullable/expected/post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import * as z from "zod"
import { CompleteUser, RelatedUserModel } from "./index"

export const PostModel = z.object({
id: z.number().int(),
authorId: z.number().int(),
})

export interface CompletePost extends z.infer<typeof PostModel> {
author?: CompleteUser | null
}

/**
* RelatedPostModel contains all relations on your model in addition to the scalars
*
* NOTE: Lazy required in case of potential circular dependencies within schema
*/
export const RelatedPostModel: z.ZodSchema<CompletePost> = z.lazy(() => PostModel.extend({
author: RelatedUserModel.nullable(),
}))
26 changes: 26 additions & 0 deletions src/test/functional/nullable/expected/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as z from "zod"
import { CompletePost, RelatedPostModel } from "./index"

// Helper schema for JSON fields
type Literal = boolean | number | string
type Json = Literal | { [key: string]: Json } | Json[]
const literalSchema = z.union([z.string(), z.number(), z.boolean()])
const jsonSchema: z.ZodSchema<Json> = z.lazy(() => z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]))

export const UserModel = z.object({
id: z.number().int(),
meta: jsonSchema,
})

export interface CompleteUser extends z.infer<typeof UserModel> {
posts?: CompletePost | null
}

/**
* RelatedUserModel contains all relations on your model in addition to the scalars
*
* NOTE: Lazy required in case of potential circular dependencies within schema
*/
export const RelatedUserModel: z.ZodSchema<CompleteUser> = z.lazy(() => UserModel.extend({
posts: RelatedPostModel.nullable(),
}))
40 changes: 40 additions & 0 deletions src/test/functional/nullable/prisma/.client/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Utility Types
*/

/**
* From https://github.com/sindresorhus/type-fest/
* Matches a JSON object.
* This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from.
*/
export type JsonObject = { [Key in string]?: JsonValue }

/**
* From https://github.com/sindresorhus/type-fest/
* Matches a JSON array.
*/
export interface JsonArray extends Array<JsonValue> {}

/**
* From https://github.com/sindresorhus/type-fest/
* Matches any valid JSON value.
*/
export type JsonValue = string | number | boolean | JsonObject | JsonArray | null

/**
* Model User
*
*/
export type User = {
id: number
meta: JsonValue
}

/**
* Model Post
*
*/
export type Post = {
id: number
authorId: number
}
30 changes: 30 additions & 0 deletions src/test/functional/nullable/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

datasource db {
provider = "postgresql"
url = ""
}

generator client {
provider = "prisma-client-js"
output = ".client"
}

generator zod {
provider = "zod-prisma"
output = "../actual/"
useNullish = false
}

model User {
id Int @id @default(autoincrement())
meta Json?
posts Post?
}

model Post {
id Int @id @default(autoincrement())
authorId Int @unique
author User? @relation(fields: [authorId], references: [id])
}
10 changes: 8 additions & 2 deletions src/test/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ describe('types Package', () => {
documentation: ['@zod.max(64)', '@zod.min(1)'].join('\n'),
}

const constructor = getZodConstructor(field)
const constructor = getZodConstructor(field, undefined, {
modelCase: 'camelCase',
modelSuffix: '',
})

expect(constructor).toBe('z.string().array().max(64).min(1).nullish()')
})
Expand All @@ -38,7 +41,10 @@ describe('types Package', () => {
type: 'SomeUnknownType',
}

const constructor = getZodConstructor(field)
const constructor = getZodConstructor(field, undefined, {
modelCase: 'camelCase',
modelSuffix: '',
})

expect(constructor).toBe('z.unknown()')
})
Expand Down
12 changes: 10 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import type { DMMF } from '@prisma/generator-helper'
import { computeCustomSchema, computeModifiers } from './docs'
import { Config } from './config'

export const getZodConstructor = (
field: DMMF.Field,
getRelatedModelName = (name: string | DMMF.SchemaEnum | DMMF.OutputType | DMMF.SchemaArg) =>
name.toString()
name.toString(),
config: Config
) => {
let zodType = 'z.unknown()'
let extraModifiers: string[] = ['']
Expand Down Expand Up @@ -51,7 +53,13 @@ export const getZodConstructor = (
zodType = computeCustomSchema(field.documentation) ?? zodType
extraModifiers.push(...computeModifiers(field.documentation))
}
if (!field.isRequired && field.type !== 'Json') extraModifiers.push('nullish()')
if (!field.isRequired && field.type !== 'Json') {
if (config && config.useNullish === false) {
extraModifiers.push('nullable()')
} else {
extraModifiers.push('nullish()')
}
}
// if (field.hasDefaultValue) extraModifiers.push('optional()')

return `${zodType}${extraModifiers.join('.')}`
Expand Down