GraphQL和表单验证错误

时间:2015-09-18 23:22:35

标签: validation error-handling graphql

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

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

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

5 个答案:

答案 0 :(得分:16)

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

// 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

或者,在编译要返回给调用者的用户错误列表时,创建可以用来代替普通字符串的type 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.' }
    ]
  }
}

答案 1 :(得分:1)

检查此包裹。它可以通过graphql响应中的errors数组轻松发送机器可读错误。然后,您可以将错误提供给您的前端并采取措施和/或提醒用户发生了什么:

https://github.com/thebigredgeek/apollo-errors

答案 2 :(得分:0)

我使用一个小包装-graphql-validation来验证项目中的表单。包裹validator.js。如此简单易用。

示例:

const { validator, validate } = require('graphql-validation'); // Import module

const resolver = {
  Mutation: {
    createPost: validator([ // <-- Validate here
      validate('title').not().isEmpty({ msg: 'Title is required' }),
      validate('content').isLength({ min: 10, max: 20 }),
    ], (parent, args, context, info) => {
      if (context.validateErrors.length > 0) {
        // Validate failed
        console.log(context.validateErrors); // Do anything with this errors

        return;
      }

      // Validate successfully, time to create new post
    }),
  },
};
Input: { title: '', content: 'Hi!' }

// console.log(context.validateErrors);
Output: [
  { param: 'title', msg: 'Title is required' },
  { param: 'content', msg: 'Invalid value' },
]

希望它有用。

答案 3 :(得分:0)

我创建了一个npm module,用于以更好的方式处理GraphQL中的验证。请检查validate-graphql npm软件包。

答案 4 :(得分:0)

最好将验证/功能检查放入服务层。

GraphQL只是您应用程序的一个入口点。因此,它不应该进行验证和功能检查。

如果您想到的应用程序具有多个访问层(REST和GraphQL)。您将通过在GraphQL层中添加验证检查来复制代码。

最好的方法是拥有一个代码层来处理此问题,例如UserService。这将保持您进行验证和功能检查的逻辑。

GraphQL和REST API只是格式化程序,将响应转换为相应响应类型的可接受格式。下面是一个示例,仅供说明:

class UserService {
    public function updateName(string $name) {
        // validation/capability check code here.
        // if validation fails, throw a user input exception or appropriate exception 
        //return value.
    }
}
GraphQl Mutation
class UserResolver {
    public function updateUserName(array $args, context $context) {
        try {
            $user = (new UserService() )->updateName(args['name']);
            return [
                'user' => $user
            ];
        } catch (UserInputException $exception) {
            return [
                'error' => $exception,
                'user' => null
            ];
        }
    }
}
REST API Controller
class UserController {
    public function updateUserName(string $name) {
        try {
            $user = (new UserService() )->updateName($name);

            return [
                'user' => $user
            ];
        } catch (UserInputException $exception) {
            return [
                'error' => $exception->message,
            ];
        }
    }
}

通过以这种方式在Service类中使用异常,您还可以选择要在响应中返回的异常(可以是GraphQL或REST响应)。

我们应该只将GraphQL视为访问层。解析程序功能应尽可能简单/简单,并且不应包含业务逻辑,验证和功能检查。

相关问题