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

问题描述

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

  {errors:{field1:is required} } 

使用GraphQL时,我们如何处理和提供这些错误?数据验证的实现方式和方式(应该是GraphQL的一部分,还是应该在每个解析函数内)?

解决方案

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

  // data / mutations / createUser.js 
import {
GraphQLObjectType as ObjectType,
GraphQLNonNull as NonNull,
GraphQLList as List,
GraphQLString as StringType
} from'graphql';
从验证器导入验证器;
从'../types/UserType'导入UserType

export default {
type:new ObjectType({
name:'CreateUserResult',
fields:{
user:{type:UserType}
错误:{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','邮箱不能为空。
} else if(!validator.isLength(email,{max:100})){
errors.push(... ['email','电子邮件必须最多100个字符。']);
}

//等

return {user,errors};
}
};

查看我的博客文章 -



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



GraphQL Query



 突变{
createUser(email:[email protected],密码:Passw0rd){
user {id,email},
errors {key,message}
}
}



查询响应



  {
data:{
user:null,
错误:[
{key:'',message:'无法创建新用户帐户'},
{key:'email',message:'具有此电子邮件的用户已存在''
]
}
}


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"}}

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)?

解决方案

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 };
  }
};

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

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.

GraphQL Query

mutation {
  createUser(email: "[email protected]", password: "Passw0rd") {
    user { id, email },
    errors { key, message }
  }
}

Query Response

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

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

10-21 12:00