GraphQL 和表单验证错误 [英] GraphQL and form validation errors

查看:18
本文介绍了GraphQL 和表单验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个将数据发布到 API 服务器的表单.API 服务器验证输入并返回 JSON 对象.如果输入无效,则返回如下所示的错误对象.

Let's say you have a form which posts data to API server. The API server validates the input and returns JSON object. If the input is invalid an error objects like the one below is returned.

{errors: {field1: "is required"}}

在使用 GraphQL 时,我们如何处理和处理此类错误?应该如何以及在哪里实现数据验证(它应该是 GraphQL 的一部分还是应该在每个解析函数中)?

How do we handle and serve these kind of errors when using GraphQL? How and where should data validation be implemented (should that be part of GraphQL or should it be inside each resolve function)?

推荐答案

通过 resolve 方法中的验证逻辑,您可以完全控制生成的用户错误.下面是一个例子:

With validation logic inside the resolve method, you have complete control over the generated user errors. Here is an example:

// data/mutations/createUser.js
import {
  GraphQLObjectType as ObjectType,
  GraphQLNonNull as NonNull,
  GraphQLList as List,
  GraphQLString as StringType
} from 'graphql';
import validator from 'validator';
import UserType from '../types/UserType';

export default {
  type: new ObjectType({
    name: 'CreateUserResult',
    fields: {
      user: { type: UserType },
      errors: { type: new NonNull(new List(StringType)) }
    }
  }),
  args: {
    email: { type: new NonNull(StringType) },
    password: { type: new NonNull(StringType) }
  },
  resolve(_, { email, password }) {
    let user = null;
    let errors = [];

    if (validator.isNull(email)) {
      errors.push(...['email', 'The email filed must not be empty.']);
    } else if (!validator.isLength(email, { max: 100})) {
      errors.push(...['email', 'The email must be at a max 100 characters long.']);
    }

    // etc.

    return { user, errors };
  }
};

请参阅我关于此主题的博客文章 - GraphQL 中的验证和用户错误突变

See my blog post on this subject - Validation and User Errors in GraphQL Mutations

或者,创建 type UserErrorType { key: String!, message: String!} 当您编译要返回给调用者的用户错误列表时,可以使用它代替纯字符串.

Alternatively, create type UserErrorType { key: String!, message: String! } that can be used instead of plain strings when you compile the list of user errors to be returned to the caller.

mutation {
  createUser(email: "hello@tarkus.me", password: "Passw0rd") {
    user { id, email },
    errors { key, message }
  }
}

查询响应

{
  data: {
    user: null,
    errors: [
      { key: '', message: 'Failed to create a new user account.' },
      { key: 'email', message: 'User with this email already exists.' }
    ]
  }
}

这篇关于GraphQL 和表单验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆