Skip to content

whygee-dev/zod-nestjs-graphql

Repository files navigation

Zod => NestJS GraphQL

A utility library to transform Zod schemas into TypeGraphQL object and input types.

Installation

With npm:

  npm i zod-nestjs-graphql

With yarn:

  yarn add zod-nestjs-graphql

With pnpm:

  pnpm add zod-nestjs-graphql

Usage/Examples

Features:

  • All primitive scalars ( String, Float, Int, DateTime )
  • Nested z.object() and z.array()
  • Enums ( z.nativeEnum() and z.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

Roadmap

  • Mapping describe()
  • Validation pipe for inputs
  • ? ( Open a feature request )

Acknowledgements

Contributing

Contributions are always welcome!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published