no_undefined_variables.go

 1package validator
 2
 3import (
 4	"github.com/vektah/gqlparser/ast"
 5	. "github.com/vektah/gqlparser/validator"
 6)
 7
 8func init() {
 9	AddRule("NoUndefinedVariables", func(observers *Events, addError AddErrFunc) {
10		observers.OnValue(func(walker *Walker, value *ast.Value) {
11			if walker.CurrentOperation == nil || value.Kind != ast.Variable || value.VariableDefinition != nil {
12				return
13			}
14
15			if walker.CurrentOperation.Name != "" {
16				addError(
17					Message(`Variable "%s" is not defined by operation "%s".`, value, walker.CurrentOperation.Name),
18					At(walker.CurrentOperation.Position),
19				)
20			} else {
21				addError(
22					Message(`Variable "%s" is not defined.`, value),
23					At(value.Position),
24				)
25			}
26		})
27	})
28}