npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nexus-validate-zod

v1.5.5

Published

Validation using Zod package for Nexus.

Downloads

462

Readme

nexus-validate-zod

npm npm bundle size

Add extra validation to GraphQL Nexus in an easy and expressive way.

const UserMutation = extendType({
  type: 'Mutation',
  definition(t) {
    t.field('createUser', {
      type: 'User',

      // add arguments
      args: {
        email: stringArg(),
        age: intArg(),
      },

      // add the extra validation
      validate: {
        email: z.string().email(),
        age: z.number().min(18),
      },
    });
  },
});

Documentation

Installation

# npm
npm i nexus-validate-zod zod

# yarn
yarn add nexus-validate-zod zod

# pnpm
pnpm add nexus-validate-zod zod

nexus-validate-zod uses zod under the hood so you need to install that too. nexus and graphql are also required, but if you are using Nexus then both of those should already be installed.

Add the plugin to Nexus:

Once installed you need to add the plugin to your nexus schema configuration:

import { makeSchema } from 'nexus';
import { validatePlugin } from 'nexus-validate-zod';

const schema = makeSchema({
  ...
  plugins: [
    ...
    validatePlugin(),
  ],
});

Usage

The validate method can be added to any field with args:

const UserMutation = extendType({
  type: 'Mutation',
  definition(t) {
    t.field('createUser', {
      type: 'User',
      args: {
        email: stringArg(),
      },
      validate: {
        // validate that email is an actual email
        email: z.string().email(),
      },
    });
  },
});

Trying to call the above with an invalid email will result in the following error:

{
  "errors": [
    {
      "message": "Validation failed",
      "extensions": {
        "validationErrors": {
            "email": "Invalid email"
        },
        "code": "BAD_USER_INPUT"
      }
      ...
    }
  ]
}

Custom validations

If you don't want to use the built-in validation rules, you can roll your own by throwing an error if an argument is invalid, and returning void if everything is OK.

import { UserInputError } from 'nexus-validate';
t.field('createUser', {
  type: 'User',
  args: {
    email: stringArg(),
  },
  // use args and context to check if email is valid
  validate(args, context) {
    if (args.email !== context.user.email) {
      throw new UserInputError('not your email', {
        invalidArgs: ['email'],
      });
    }
  },
});

Custom errors

The plugin provides a formatError option where you can format the error however you'd like:

import { UserInputError } from 'apollo-server';
import { validatePlugin, ValidationError } from 'nexus-validate';

const schema = makeSchema({
  ...
  plugins: [
    ...
    validatePlugin({
      formatError: ({ error }) => {
        if (error instanceof ZodError) {
          // convert error to UserInputError from apollo-server
          return new UserInputError("Your custom error message", {
            validationErrors: { ... },
          });
        }

        return error;
      },
    }),
  ],
});

Custom error messages

If you want to change the error message for the validation rules, that's usually possible by passing a message to the rule:

validate: {
  email: z
          .string({
            required_error: 'Email is required',
          })
          .email('Email must be valid email'),
};

API

validate(args: Args, ctx: Context) => Promise<ValidationSchema | boolean>

Args

The Args argument will return whatever you passed in to args in your field definition:

t.field('createUser', {
  type: 'User',
  args: {
    email: stringArg(),
    age: numberArg(),
  },
  // email and age will be typed as a string and a number
  validate: ({ email, age }) => {}
}

Context

Context is your GraphQL context, which can give you access to things like the current user or your data sources. This will let you validation rules based on the context of your API.

t.field('createUser', {
  type: 'User',
  args: {
    email: stringArg(),
  },
  validate: async ({ email }, { prisma }) => {
    const count = await prisma.user.count({ where: { email } });
    if (count > 1) {
      throw new Error('email already taken');
    }
  },
});

Examples