Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@peacechen/nexus-validate

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@peacechen/nexus-validate

Validation plugin for Nexus JS.

  • 1.4.2
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

nexus-validate plugin

npm npm bundle size build-publish codecov

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: ({ string, number }) => ({
        email: string().email(),
        age: number().moreThan(18).integer(),
      }),
    });
  },
});

Documentation

Installation

# npm
npm i @peacechen/nexus-validate yup

# yarn
yarn add @peacechen/nexus-validate yup

nexus-validate uses yup 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 '@peacechen/nexus-validate';

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: ({ string }) => ({
        // validate that email is an actual email
        email: string().email(),
      }),
    });
  },
});

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

{
  "errors": [
    {
      "message": "email must be a valid email",
      "extensions": {
        "invalidArgs": ["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 '@peacechen/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 '@peacechen/nexus-validate';

const schema = makeSchema({
  ...
  plugins: [
    ...
    validatePlugin({
      formatError: ({ error }) => {
        if (error instanceof ValidationError) {
          // convert error to UserInputError from apollo-server
          return new UserInputError(error.message, {
            invalidArgs: [error.path],
          });
        }

        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: ({ string }) => ({
  email: string()
    .email('must be a valid email address')
    .required('email is required'),
});

API

validate(rules: ValidationRules, args: Args, ctx: Context) => Promise<Schema | boolean>

ValidationRules

TypeDocsExample
stringdocsstring().email().max(20).required()
numberdocsnumber().moreThan(18).number()
booleandocsboolean()
datedocsdate().min('2000-01-01').max(new Date())
objectdocsobject({ name: string() })
arraydocsarray.min(5).of(string())

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

License

nexus-validate is provided under the MIT License. See LICENSE for details.

This library is based off of @joosepalviste/nexus-validate which was forked from nexus-validate . The latter appears to be abandoned. The hope is that this will be a community-supported version. Maintainers are welcome.

FAQs

Package last updated on 16 Aug 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc