{"id":19233656,"url":"https://github.com/filipstefansson/nexus-validate","last_synced_at":"2025-04-21T04:33:18.801Z","repository":{"id":40362393,"uuid":"331973618","full_name":"filipstefansson/nexus-validate","owner":"filipstefansson","description":"🔑 Add argument validation to your GraphQL Nexus API.","archived":false,"fork":false,"pushed_at":"2022-09-02T07:33:56.000Z","size":148,"stargazers_count":35,"open_issues_count":0,"forks_count":8,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-01T09:47:10.773Z","etag":null,"topics":["graphql","nexus","prisma2","validation","yup"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/filipstefansson.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-01-22T14:42:59.000Z","updated_at":"2024-08-08T14:03:08.000Z","dependencies_parsed_at":"2023-01-17T18:46:10.689Z","dependency_job_id":null,"html_url":"https://github.com/filipstefansson/nexus-validate","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/filipstefansson%2Fnexus-validate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/filipstefansson%2Fnexus-validate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/filipstefansson%2Fnexus-validate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/filipstefansson%2Fnexus-validate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/filipstefansson","download_url":"https://codeload.github.com/filipstefansson/nexus-validate/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249996234,"owners_count":21358094,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphql","nexus","prisma2","validation","yup"],"created_at":"2024-11-09T16:11:26.152Z","updated_at":"2025-04-21T04:33:18.536Z","avatar_url":"https://github.com/filipstefansson.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# nexus-validate\n\n[![npm](https://img.shields.io/npm/v/nexus-validate)](https://www.npmjs.com/package/nexus-validate)\n[![npm bundle size](https://img.shields.io/bundlephobia/min/nexus-validate)](https://bundlephobia.com/result?p=nexus-validate)\n![build-publish](https://github.com/filipstefansson/nexus-validate/workflows/build-publish/badge.svg)\n[![codecov](https://codecov.io/gh/filipstefansson/nexus-validate/branch/alpha/graph/badge.svg?token=MR3OPGNYBU)](https://codecov.io/gh/filipstefansson/nexus-validate)\n\nAdd extra validation to [GraphQL Nexus](https://github.com/graphql-nexus/nexus) in an easy and expressive way.\n\n```ts\nconst UserMutation = extendType({\n  type: 'Mutation',\n  definition(t) {\n    t.field('createUser', {\n      type: 'User',\n\n      // add arguments\n      args: {\n        email: stringArg(),\n        age: intArg(),\n      },\n\n      // add the extra validation\n      validate: ({ string, number }) =\u003e ({\n        email: string().email(),\n        age: number().moreThan(18).integer(),\n      }),\n    });\n  },\n});\n```\n\n## Documentation\n\n- [Installation](#installation)\n- [Usage](#usage)\n  - [Custom validations](#custom-validations)\n  - [Custom errors](#custom-errors)\n  - [Custom error messages](#custom-error-messages)\n- [API](#api)\n- [Examples](#examples)\n\n## Installation\n\n```console\n# npm\nnpm i nexus-validate yup\n\n# yarn\nyarn add nexus-validate yup\n```\n\n\u003e `nexus-validate` uses [`yup`](https://github.com/jquense/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.\n\n### Add the plugin to Nexus:\n\nOnce installed you need to add the plugin to your nexus schema configuration:\n\n```ts\nimport { makeSchema } from 'nexus';\nimport { validatePlugin } from 'nexus-validate';\n\nconst schema = makeSchema({\n  ...\n  plugins: [\n    ...\n    validatePlugin(),\n  ],\n});\n```\n\n## Usage\n\nThe `validate` method can be added to any field with `args`:\n\n```ts\nconst UserMutation = extendType({\n  type: 'Mutation',\n  definition(t) {\n    t.field('createUser', {\n      type: 'User',\n      args: {\n        email: stringArg(),\n      },\n      validate: ({ string }) =\u003e ({\n        // validate that email is an actual email\n        email: string().email(),\n      }),\n    });\n  },\n});\n```\n\nTrying to call the above with an invalid email will result in the following error:\n\n```json\n{\n  \"errors\": [\n    {\n      \"message\": \"email must be a valid email\",\n      \"extensions\": {\n        \"invalidArgs\": [\"email\"],\n        \"code\": \"BAD_USER_INPUT\"\n      }\n      ...\n    }\n  ]\n}\n```\n\n### Custom validations\n\nIf 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.\n\n```ts\nimport { UserInputError } from 'nexus-validate';\nt.field('createUser', {\n  type: 'User',\n  args: {\n    email: stringArg(),\n  },\n  // use args and context to check if email is valid\n  validate(_, args, context) {\n    if (args.email !== context.user.email) {\n      throw new UserInputError('not your email', {\n        invalidArgs: ['email'],\n      });\n    }\n  },\n});\n```\n\n### Custom errors\n\nThe plugin provides a `formatError` option where you can format the error however you'd like:\n\n```ts\nimport { UserInputError } from 'apollo-server';\nimport { validatePlugin, ValidationError } from 'nexus-validate';\n\nconst schema = makeSchema({\n  ...\n  plugins: [\n    ...\n    validatePlugin({\n      formatError: ({ error }) =\u003e {\n        if (error instanceof ValidationError) {\n          // convert error to UserInputError from apollo-server\n          return new UserInputError(error.message, {\n            invalidArgs: [error.path],\n          });\n        }\n\n        return error;\n      },\n    }),\n  ],\n});\n```\n\n### Custom error messages\n\nIf you want to change the error message for the validation rules, that's usually possible by passing a message to the rule:\n\n```ts\nvalidate: ({ string }) =\u003e ({\n  email: string()\n    .email('must be a valid email address')\n    .required('email is required'),\n});\n```\n\n## API\n\n##### `validate(rules: ValidationRules, args: Args, ctx: Context) =\u003e Promise\u003cSchema | boolean\u003e`\n\n### ValidationRules\n\n| Type    | Docs                                           | Example                                    |\n| :------ | :--------------------------------------------- | :----------------------------------------- |\n| string  | [docs](https://github.com/jquense/yup#string)  | `string().email().max(20).required()`      |\n| number  | [docs](https://github.com/jquense/yup#number)  | `number().moreThan(18).number()`           |\n| boolean | [docs](https://github.com/jquense/yup#boolean) | `boolean()`                                |\n| date    | [docs](https://github.com/jquense/yup#date)    | `date().min('2000-01-01').max(new Date())` |\n| object  | [docs](https://github.com/jquense/yup#object)  | `object({ name: string() })`               |\n| array   | [docs](https://github.com/jquense/yup#array)   | `array.min(5).of(string())`                |\n\n### Args\n\nThe `Args` argument will return whatever you passed in to `args` in your field definition:\n\n```ts\nt.field('createUser', {\n  type: 'User',\n  args: {\n    email: stringArg(),\n    age: numberArg(),\n  },\n  // email and age will be typed as a string and a number\n  validate: (_, { email, age }) =\u003e {}\n}\n```\n\n### Context\n\n`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.\n\n```ts\nt.field('createUser', {\n  type: 'User',\n  args: {\n    email: stringArg(),\n  },\n  validate: async (_, { email }, { prisma }) =\u003e {\n    const count = await prisma.user.count({ where: { email } });\n    if (count \u003e 1) {\n      throw new Error('email already taken');\n    }\n  },\n});\n```\n\n## Examples\n\n- [Hello World Example](examples/hello-world)\n\n## License\n\n**nexus-validate** is provided under the MIT License. See LICENSE for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffilipstefansson%2Fnexus-validate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffilipstefansson%2Fnexus-validate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffilipstefansson%2Fnexus-validate/lists"}