@vantreeseba/graphql-zod
v0.1.0
Published
Auto Zod validation schema builder from GraphQL typed documents (runtime).
Readme
@vantreeseba/graphql-zod
Builds a Zod schema for the variables of a GraphQL operation, so the rules an operation already states (which variables are required, which are numbers, which may be null) don't have to be written again by hand for a form or an endpoint.
inferZodSchema(document) needs only the document, not the GraphQL schema. To resolve nested inputs, or to validate results, generate the schemas at build time with @vantreeseba/graphql-zod-codegen.
Install
npm install @vantreeseba/graphql-zod graphql zodIt is ESM only. graphql (16 or later) and zod (3 or later) are peer dependencies.
Quick start
Save this as quick-start.mjs and run node quick-start.mjs.
import { inferZodSchema } from '@vantreeseba/graphql-zod';
import { parse } from 'graphql';
const document = parse(`
mutation UpdateUser($id: ID!, $name: String!, $age: Int) {
updateUser(id: $id, name: $name, age: $age) { id }
}
`);
const schema = inferZodSchema(document);
// Numeric strings, such as form values, become numbers.
console.log(schema.parse({ id: '1', name: 'Ada', age: '36' }));
// { id: '1', name: 'Ada', age: 36 }
console.log(schema.safeParse({ id: '1', name: '' }).error.issues[0].message);
// Name is requiredIn TypeScript the document needs a cast, which Validate variables at run time shows.
Documentation
- Install and a first schema
- Validate variables at run time:
scalarsandoverrides - Type mapping: scalars, required strings, nullability, lists
- Common mistakes
The installed package has these pages too, with an index of every export in its llms.txt.
Roadmap
Planned work is in TODO.md.
