graphql-go / graphql

An implementation of GraphQL for Go / Golang
MIT License
9.87k stars 839 forks source link

make writing validation rules easy #552

Open koron opened 4 years ago

koron commented 4 years ago

This PR eases writing and using custom validation rules. It includes two changes:

  1. make graphql.Do() be able to change validation rules by adding ValidationRule field to graphql.Params and use it for graphql.ValidateDocument()
  2. make graphql.getArgumentValues() be accessible from other packages by adding graphql.GetArgumentValues() as a wrapper of it.

Background

I wrote a cost analysis package:koron-go/gqlcost for graphql-go/graphql as a validation rule. (It is a port of pa-bru/graphql-cost-analysis) I use two problematic hacky methods to write it:

  1. modify graphql.SpecifiedRules (refer: koron-go/gqlcost:gqlcost.go#L19-L28)

    There are no ways to use custom validation rules with graphql.Do() currently. It is highly problematic to modify graphql.SpecifiedRules because other packages use graphql are affected by this.

  2. Copy pile of codes from graphql-go/graphql:values.go to just access field's argument values (refer: koron-go/gqlcost:values.go#L3-L5)

    I found that there are some cases to want access field arguments value when writing validation rules. cost-analysis package uses those to calculate cost with multipliers. graphql-go/graphql has a function to do it, but it is private and not exported. It wil be great, if those functions are public for other packages which provides custom validation rules.

I want to resolve these problems by this PR.

coveralls commented 4 years ago

Coverage Status

Coverage increased (+0.004%) to 92.43% when pulling 3e0d192fd448813de71d115f777b662ac144b3f6 on koron:make-validationrule-extensible into d6b7434614ec6dd976827ff2a59483d35fae46e4 on graphql-go:master.