All Projects → filipstefansson → nexus-validate

filipstefansson / nexus-validate

Licence: other
🔑 Add argument validation to your GraphQL Nexus API.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to nexus-validate

boilerplate-nexus-prisma-apollo-graphql-express
Boilerplate project for a graphql server using nexus-prisma and apollo-server-express
Stars: ✭ 31 (+6.9%)
Mutual labels:  nexus, prisma2
validator
💯Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
Stars: ✭ 9,721 (+33420.69%)
Mutual labels:  validation
validation
Validation in Ruby objects
Stars: ✭ 18 (-37.93%)
Mutual labels:  validation
validation
Validation on Laravel 5.X|6.X|7.X|8.X
Stars: ✭ 26 (-10.34%)
Mutual labels:  validation
NeverBounceAPI-PHP
This package provides convenient methods to integrate the NeverBounce API into your project.
Stars: ✭ 22 (-24.14%)
Mutual labels:  validation
laravel-pwned-passwords
Simple Laravel validation rule that allows you to prevent or limit the re-use of passwords that are known to be pwned (unsafe). Based on TroyHunt's Have I Been Pwned (https://haveibeenpwned.com)
Stars: ✭ 67 (+131.03%)
Mutual labels:  validation
core
Microservice abstract class
Stars: ✭ 37 (+27.59%)
Mutual labels:  validation
flask-pydantic
flask extension for integration with the awesome pydantic package
Stars: ✭ 181 (+524.14%)
Mutual labels:  validation
webargs-starlette
Declarative request parsing and validation for Starlette with webargs
Stars: ✭ 36 (+24.14%)
Mutual labels:  validation
Swiftz-Validation
A data structure for validations. It implements the applicative functor interface
Stars: ✭ 15 (-48.28%)
Mutual labels:  validation
oolong
oolong 🍵 : create and administrate validation tests for typical automated content analysis tools.
Stars: ✭ 40 (+37.93%)
Mutual labels:  validation
thai-citizen-id-validator
🦉 Validate Thai Citizen ID with 0 dependencies 🇹🇭
Stars: ✭ 35 (+20.69%)
Mutual labels:  validation
xrechnung-schematron
Schematron rules for the German CIUS (XRechnung) of EN16931:2017
Stars: ✭ 19 (-34.48%)
Mutual labels:  validation
robotframework-aristalibrary
Robot Framework library for Arista EOS
Stars: ✭ 14 (-51.72%)
Mutual labels:  validation
ttv
A command line tool for splitting files into test, train, and validation sets.
Stars: ✭ 38 (+31.03%)
Mutual labels:  validation
checker
Golang parameter validation, which can replace go-playground/validator, includes ncluding Cross Field, Map, Slice and Array diving, provides readable,flexible, configurable validation.
Stars: ✭ 62 (+113.79%)
Mutual labels:  validation
svelte-form
JSON Schema form for Svelte v3
Stars: ✭ 47 (+62.07%)
Mutual labels:  validation
excel validator
Python script to validate data in Excel files
Stars: ✭ 14 (-51.72%)
Mutual labels:  validation
apple-receipt
Apple InAppPurchase Receipt - Models, Parser, Validator
Stars: ✭ 25 (-13.79%)
Mutual labels:  validation
fefe
Validate, sanitize and transform values with proper TypeScript types and zero dependencies.
Stars: ✭ 34 (+17.24%)
Mutual labels:  validation

nexus-validate

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 nexus-validate yup

# yarn
yarn add 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 '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 '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 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

Type Docs Example
string docs string().email().max(20).required()
number docs number().moreThan(18).number()
boolean docs boolean()
date docs date().min('2000-01-01').max(new Date())
object docs object({ name: string() })
array docs array.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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].