假设您有一个将数据发布到API服务器的表单. API服务器验证输入并返回
JSON对象.如果输入无效,则返回如下所示的错误对象.
{errors: {field1: "is required"}}
使用GraphQL时,我们如何处理和提供这些错误?数据验证的实现方式和位置(应该是GraphQL的一部分,还是应该在每个解析函数内)?
解决方法
通过解析方法中的验证逻辑,可以完全控制生成的用户错误.这是一个例子:
// 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 }; } };
查看我的博客文章这个主题 – Validation and User Errors in GraphQL Mutations
或者,创建类型UserErrorType {key:String !,message:String! }当您编译要返回给调用者的用户错误列表时,可以使用而不是纯字符串.
GraphQL查询
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.' } ] } }