A utility library to transform Zod schemas into TypeGraphQL object and input types.
With npm:
npm i zod-nestjs-graphqlWith yarn:
yarn add zod-nestjs-graphqlWith pnpm:
pnpm add zod-nestjs-graphqlFeatures:
- All primitive scalars (
String,Float,Int,DateTime) - Nested
z.object()andz.array() - Enums (
z.nativeEnum()andz.enum()) - Custom scalars / models mapping
- Generated model / input typings
- Custom separator for generated nested models
- Unit tested
Supported Zod types and their corresponding GraphQL Scalar:
-
z.string()( String ) -
z.boolean()( Boolean ) -
z.number()( Float ) -
z.number().int()( Int ) -
z.date()( DateTime ) -
z.nativeEnum() -
z.enum() -
z.object() -
z.array() - Custom scalars
zodToModel
import { z } from 'zod'
import { zodToModel, InferModel } from 'zod-nestjs-graphql'
const model = zodToModel(
z.object({
fullName: z.string(),
age: z.number(),
email: z.string().email(),
phone: z.string().optional(),
}),
{
name: 'User',
}
)
type Model = InferModel<typeof model>zodToInput
import { z } from 'zod'
import { zodToInput, InferModel } from 'zod-nestjs-graphql'
const input = zodToInput(
z.object({
fullName: z.string(),
age: z.number(),
email: z.string().email(),
phone: z.string().optional(),
}),
{
name: 'User',
}
)
type Input = InferModel<typeof input>Custom mapping ( works with custom scalars and zodToInput the same way )
import { z } from 'zod'
import { zodToModel, InferModel } from 'zod-nestjs-graphql'
@ObjectType()
class UserProfile {
@Field()
address?: string
}
const model = zodToModel(
z.object({
fullName: z.string(),
profile: z.object({ address: z.string().optional() }),
nestedObject: z.object({
evenMoreNestedObject: z.object({
address: z.string().optional(),
}),
}),
}),
{
name: 'User',
map: {
profile: UserProfile,
'nestedObjected.evenMoreNestedObject': UserProfile,
},
}
)
type Model = InferModel<typeof model>Check out examples folder for advanced usage
- Mapping describe()
- Validation pipe for inputs
- ? ( Open a feature request )
- Inspired by nestjs-graphql-zod
- Initially developed for internal usage @ Beeldi
Contributions are always welcome!