graphql/graphql-js

Validation in Input types proposal

已关闭

#361 创建于 2016年4月20日

 (47 条评论) (103 个反应) (0 位负责人)TypeScript (2,223 个派生)batch import
help wanted

仓库指标

星标
 (19,825 个星标)
PR 合并指标
 (平均合并 12天 6小时) (30 天内合并 42 个 PR)

描述

Validations in GraphQL-js

I would like to open a discussion around validation.

I think could be a great idea permit validation in input elements: GraphQLInputField and GraphQLArgument. This would not involve any spec change as it relies on the implementation (as the resolve method).

Right now is possible to achieve this by using a custom GraphQLScalar per validation. However, by doing this we have to create a new type just for validation and is not easy to compose multiple validation rules without creating a type for each composition.

Also, is possible to achieve it by add the validation logic in the resolver method, however things get trickier when we want to validate nested input data.

So, will be much simpler to have this in the implementation.

Handling errors

We could have two ways for handling validation errors:

  • Not executing the query
  • Executing the query excluding the fields with non-valid input, and add the validation error to the context.

Example usage

const queryType = new GraphQLObjectType({
  name: 'Query',
  fields: () => ({
    getUser: {
      type: User,
      args: {
        email: {
          description: 'The email of the user',
          validators: [email_validator],
          type: String
        }
      },
      resolve: (root, { email }) => {
        // We know we received a proper input, so this simplifies the resolver logic
        return getUserByEmail(email)
      },
    },
  })
});

Implementation

The implementation of this should be really simple, as it could be achieved by creating a new validation rule.

贡献者指南