From 5a432d4ffac0b12abb8b9381f19327f3088a7a71 Mon Sep 17 00:00:00 2001 From: Nathaniel Maman Date: Mon, 26 Oct 2015 23:47:34 +0200 Subject: [PATCH 1/6] rename graphql-go to graphql --- README.md | 2 +- errors/formatted.go | 2 +- errors/graphql.go | 6 +++--- errors/located.go | 2 +- errors/syntax.go | 6 +++--- executor/abstract_test.go | 10 +++++----- executor/directives_test.go | 6 +++--- executor/executor.go | 6 +++--- executor/executor_schema_test.go | 6 +++--- executor/executor_test.go | 10 +++++----- executor/lists_test.go | 10 +++++----- executor/mutations_test.go | 10 +++++----- executor/nonnull_test.go | 10 +++++----- executor/union_interface_test.go | 6 +++--- executor/values.go | 10 +++++----- executor/variables_test.go | 12 ++++++------ graphql.go | 12 ++++++------ graphql_test.go | 2 +- language/ast/arguments.go | 2 +- language/ast/definitions.go | 2 +- language/ast/directives.go | 2 +- language/ast/document.go | 2 +- language/ast/location.go | 2 +- language/ast/name.go | 2 +- language/ast/selections.go | 2 +- language/ast/type_definitions.go | 2 +- language/ast/types.go | 2 +- language/ast/values.go | 2 +- language/lexer/lexer.go | 4 ++-- language/lexer/lexer_test.go | 2 +- language/location/location.go | 2 +- language/parser/parser.go | 8 ++++---- language/parser/parser_test.go | 8 ++++---- language/parser/schema_parser_test.go | 10 +++++----- language/printer/printer.go | 4 ++-- language/printer/printer_test.go | 8 ++++---- language/printer/schema_printer_test.go | 6 +++--- language/visitor/visitor_test.go | 8 ++++---- testutil/testutil.go | 8 ++++---- testutil/testutil_test.go | 2 +- types/definition.go | 4 ++-- types/definition_test.go | 4 ++-- types/enum_type_test.go | 8 ++++---- types/introspection.go | 4 ++-- types/introspection_test.go | 10 +++++----- types/scalars.go | 2 +- types/types.go | 2 +- types/validation_test.go | 4 ++-- validator/validator.go | 6 +++--- 49 files changed, 131 insertions(+), 131 deletions(-) diff --git a/README.md b/README.md index c0bc1e93..f4a9b85b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -graphql-go [![Build Status](https://travis-ci.org/chris-ramon/graphql-go.svg)](https://travis-ci.org/chris-ramon/graphql-go) [![GoDoc](https://godoc.org/graphql.co/graphql?status.svg)](https://godoc.org/github.com/chris-ramon/graphql-go) [![Coverage Status](https://coveralls.io/repos/chris-ramon/graphql-go/badge.svg?branch=master&service=github)](https://coveralls.io/github/chris-ramon/graphql-go?branch=master) +graphql [![Build Status](https://travis-ci.org/chris-ramon/graphql.svg)](https://travis-ci.org/chris-ramon/graphql) [![GoDoc](https://godoc.org/graphql.co/graphql?status.svg)](https://godoc.org/github.com/chris-ramon/graphql) [![Coverage Status](https://coveralls.io/repos/chris-ramon/graphql/badge.svg?branch=master&service=github)](https://coveralls.io/github/chris-ramon/graphql?branch=master) ===== An *work in progress* implementation of GraphQL for Go. diff --git a/errors/formatted.go b/errors/formatted.go index df4704db..010b8795 100644 --- a/errors/formatted.go +++ b/errors/formatted.go @@ -2,7 +2,7 @@ package graphqlerrors import ( "errors" - "github.com/chris-ramon/graphql-go/language/location" + "github.com/chris-ramon/graphql/language/location" ) type GraphQLFormattedError struct { diff --git a/errors/graphql.go b/errors/graphql.go index 8777b892..6dc98928 100644 --- a/errors/graphql.go +++ b/errors/graphql.go @@ -2,9 +2,9 @@ package graphqlerrors import ( "fmt" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/language/source" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/language/source" ) type GraphQLError struct { diff --git a/errors/located.go b/errors/located.go index 9a56cbca..590a52b8 100644 --- a/errors/located.go +++ b/errors/located.go @@ -1,7 +1,7 @@ package graphqlerrors import ( - "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql/language/ast" ) func NewLocatedError(err interface{}, nodes []ast.Node) *GraphQLError { diff --git a/errors/syntax.go b/errors/syntax.go index efc7267f..c934c574 100644 --- a/errors/syntax.go +++ b/errors/syntax.go @@ -4,9 +4,9 @@ import ( "fmt" "regexp" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/language/source" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/language/source" ) func NewSyntaxError(s *source.Source, position int, description string) *GraphQLError { diff --git a/executor/abstract_test.go b/executor/abstract_test.go index f272a3e6..abd60c9e 100644 --- a/executor/abstract_test.go +++ b/executor/abstract_test.go @@ -1,11 +1,11 @@ package executor_test import ( - "github.com/chris-ramon/graphql-go" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/executor/directives_test.go b/executor/directives_test.go index 36178cc3..8a8acf0d 100644 --- a/executor/directives_test.go +++ b/executor/directives_test.go @@ -1,9 +1,9 @@ package executor_test import ( - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/executor/executor.go b/executor/executor.go index 9d706932..dd65643d 100644 --- a/executor/executor.go +++ b/executor/executor.go @@ -3,9 +3,9 @@ package executor import ( "fmt" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/types" "reflect" "strings" ) diff --git a/executor/executor_schema_test.go b/executor/executor_schema_test.go index d2f23c09..96dafb3c 100644 --- a/executor/executor_schema_test.go +++ b/executor/executor_schema_test.go @@ -2,9 +2,9 @@ package executor_test import ( "fmt" - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/executor/executor_test.go b/executor/executor_test.go index 0e414c00..d0e28c75 100644 --- a/executor/executor_test.go +++ b/executor/executor_test.go @@ -3,11 +3,11 @@ package executor_test import ( "encoding/json" "fmt" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/executor/lists_test.go b/executor/lists_test.go index 6a51318c..951d5396 100644 --- a/executor/lists_test.go +++ b/executor/lists_test.go @@ -1,11 +1,11 @@ package executor_test import ( - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/executor/mutations_test.go b/executor/mutations_test.go index 1564241d..d4c55d2b 100644 --- a/executor/mutations_test.go +++ b/executor/mutations_test.go @@ -1,11 +1,11 @@ package executor_test import ( - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/executor/nonnull_test.go b/executor/nonnull_test.go index 7a6905bb..63db8385 100644 --- a/executor/nonnull_test.go +++ b/executor/nonnull_test.go @@ -5,11 +5,11 @@ import ( "sort" "testing" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" ) var syncError = "sync" diff --git a/executor/union_interface_test.go b/executor/union_interface_test.go index fef8f6d7..d2c3559b 100644 --- a/executor/union_interface_test.go +++ b/executor/union_interface_test.go @@ -1,9 +1,9 @@ package executor_test import ( - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/executor/values.go b/executor/values.go index 568776a0..6800f54f 100644 --- a/executor/values.go +++ b/executor/values.go @@ -3,11 +3,11 @@ package executor import ( "encoding/json" "fmt" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/kinds" - "github.com/chris-ramon/graphql-go/language/printer" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql/language/printer" + "github.com/chris-ramon/graphql/types" "math" "reflect" ) diff --git a/executor/variables_test.go b/executor/variables_test.go index 843242b5..5cbdc957 100644 --- a/executor/variables_test.go +++ b/executor/variables_test.go @@ -2,12 +2,12 @@ package executor_test import ( "encoding/json" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/graphql.go b/graphql.go index 1ab19e4d..b904d903 100644 --- a/graphql.go +++ b/graphql.go @@ -1,12 +1,12 @@ package gql import ( - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/language/parser" - "github.com/chris-ramon/graphql-go/language/source" - "github.com/chris-ramon/graphql-go/types" - "github.com/chris-ramon/graphql-go/validator" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/language/parser" + "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql/types" + "github.com/chris-ramon/graphql/validator" ) type GraphqlParams struct { diff --git a/graphql_test.go b/graphql_test.go index a4579ab6..3136a646 100644 --- a/graphql_test.go +++ b/graphql_test.go @@ -4,7 +4,7 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/types" "./testutil" ) diff --git a/language/ast/arguments.go b/language/ast/arguments.go index a63f2334..93cc7b60 100644 --- a/language/ast/arguments.go +++ b/language/ast/arguments.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql-go/language/kinds" + "github.com/chris-ramon/graphql/language/kinds" ) // Argument implements Node diff --git a/language/ast/definitions.go b/language/ast/definitions.go index 971a88a7..a1bfa5de 100644 --- a/language/ast/definitions.go +++ b/language/ast/definitions.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql-go/language/kinds" + "github.com/chris-ramon/graphql/language/kinds" ) type Definition interface { diff --git a/language/ast/directives.go b/language/ast/directives.go index 25949360..7dd49269 100644 --- a/language/ast/directives.go +++ b/language/ast/directives.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql-go/language/kinds" + "github.com/chris-ramon/graphql/language/kinds" ) // Directive implements Node diff --git a/language/ast/document.go b/language/ast/document.go index 2bbfbe6f..34385da9 100644 --- a/language/ast/document.go +++ b/language/ast/document.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql-go/language/kinds" + "github.com/chris-ramon/graphql/language/kinds" ) // Document implements Node diff --git a/language/ast/location.go b/language/ast/location.go index e0915aad..6f60120c 100644 --- a/language/ast/location.go +++ b/language/ast/location.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql-go/language/source" + "github.com/chris-ramon/graphql/language/source" ) type Location struct { diff --git a/language/ast/name.go b/language/ast/name.go index eed3dbbd..bcce6dd8 100644 --- a/language/ast/name.go +++ b/language/ast/name.go @@ -1,6 +1,6 @@ package ast -import "github.com/chris-ramon/graphql-go/language/kinds" +import "github.com/chris-ramon/graphql/language/kinds" // Name implements Node type Name struct { diff --git a/language/ast/selections.go b/language/ast/selections.go index d28c1045..953db218 100644 --- a/language/ast/selections.go +++ b/language/ast/selections.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql-go/language/kinds" + "github.com/chris-ramon/graphql/language/kinds" ) type Selection interface { diff --git a/language/ast/type_definitions.go b/language/ast/type_definitions.go index 44bbcaeb..e7d8a72a 100644 --- a/language/ast/type_definitions.go +++ b/language/ast/type_definitions.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql-go/language/kinds" + "github.com/chris-ramon/graphql/language/kinds" ) // TypeDefinition implements Definition diff --git a/language/ast/types.go b/language/ast/types.go index e7255bab..3233ec3a 100644 --- a/language/ast/types.go +++ b/language/ast/types.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql-go/language/kinds" + "github.com/chris-ramon/graphql/language/kinds" ) type Type interface { diff --git a/language/ast/values.go b/language/ast/values.go index 5114072d..2b484a66 100644 --- a/language/ast/values.go +++ b/language/ast/values.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql-go/language/kinds" + "github.com/chris-ramon/graphql/language/kinds" ) type Value interface { diff --git a/language/lexer/lexer.go b/language/lexer/lexer.go index cde0a105..28ad4c8f 100644 --- a/language/lexer/lexer.go +++ b/language/lexer/lexer.go @@ -3,8 +3,8 @@ package lexer import ( "fmt" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/source" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/source" ) const ( diff --git a/language/lexer/lexer_test.go b/language/lexer/lexer_test.go index 1365164c..ac56ee73 100644 --- a/language/lexer/lexer_test.go +++ b/language/lexer/lexer_test.go @@ -4,7 +4,7 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql-go/language/source" + "github.com/chris-ramon/graphql/language/source" ) type Test struct { diff --git a/language/location/location.go b/language/location/location.go index d5e44f6e..6ec9784d 100644 --- a/language/location/location.go +++ b/language/location/location.go @@ -3,7 +3,7 @@ package location import ( "regexp" - "github.com/chris-ramon/graphql-go/language/source" + "github.com/chris-ramon/graphql/language/source" ) type SourceLocation struct { diff --git a/language/parser/parser.go b/language/parser/parser.go index c514a405..6cadd34a 100644 --- a/language/parser/parser.go +++ b/language/parser/parser.go @@ -3,10 +3,10 @@ package parser import ( "fmt" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/lexer" - "github.com/chris-ramon/graphql-go/language/source" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/lexer" + "github.com/chris-ramon/graphql/language/source" ) type parseFn func(parser *Parser) (interface{}, error) diff --git a/language/parser/parser_test.go b/language/parser/parser_test.go index 964c721c..a708072a 100644 --- a/language/parser/parser_test.go +++ b/language/parser/parser_test.go @@ -8,10 +8,10 @@ import ( "io/ioutil" "strings" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/language/source" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/language/source" ) func TestAcceptsOptionToNotIncludeSource(t *testing.T) { diff --git a/language/parser/schema_parser_test.go b/language/parser/schema_parser_test.go index 3926e516..4f5f4007 100644 --- a/language/parser/schema_parser_test.go +++ b/language/parser/schema_parser_test.go @@ -4,11 +4,11 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/language/parser" - "github.com/chris-ramon/graphql-go/language/source" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/language/parser" + "github.com/chris-ramon/graphql/language/source" ) func parse(t *testing.T, query string) *ast.Document { diff --git a/language/printer/printer.go b/language/printer/printer.go index 09aa182e..b2baacf7 100644 --- a/language/printer/printer.go +++ b/language/printer/printer.go @@ -2,8 +2,8 @@ package printer import ( "fmt" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/visitor" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/visitor" "strings" ) diff --git a/language/printer/printer_test.go b/language/printer/printer_test.go index 0a8e4f12..77d15f23 100644 --- a/language/printer/printer_test.go +++ b/language/printer/printer_test.go @@ -1,10 +1,10 @@ package printer_test import ( - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/parser" - "github.com/chris-ramon/graphql-go/language/printer" - "github.com/chris-ramon/graphql-go/testutil" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/parser" + "github.com/chris-ramon/graphql/language/printer" + "github.com/chris-ramon/graphql/testutil" "io/ioutil" "reflect" "testing" diff --git a/language/printer/schema_printer_test.go b/language/printer/schema_printer_test.go index 23ea6233..bb73af3e 100644 --- a/language/printer/schema_printer_test.go +++ b/language/printer/schema_printer_test.go @@ -1,9 +1,9 @@ package printer_test import ( - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/printer" - "github.com/chris-ramon/graphql-go/testutil" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/printer" + "github.com/chris-ramon/graphql/testutil" "io/ioutil" "reflect" "testing" diff --git a/language/visitor/visitor_test.go b/language/visitor/visitor_test.go index b89d844a..ad9c6d60 100644 --- a/language/visitor/visitor_test.go +++ b/language/visitor/visitor_test.go @@ -1,10 +1,10 @@ package visitor_test import ( - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/parser" - "github.com/chris-ramon/graphql-go/language/visitor" - "github.com/chris-ramon/graphql-go/testutil" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/parser" + "github.com/chris-ramon/graphql/language/visitor" + "github.com/chris-ramon/graphql/testutil" "io/ioutil" "reflect" "strings" diff --git a/testutil/testutil.go b/testutil/testutil.go index 0b4615a5..57ae13c8 100644 --- a/testutil/testutil.go +++ b/testutil/testutil.go @@ -6,10 +6,10 @@ import ( "strconv" "testing" - "github.com/chris-ramon/graphql-go/executor" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/parser" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/executor" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/parser" + "github.com/chris-ramon/graphql/types" "github.com/kr/pretty" ) diff --git a/testutil/testutil_test.go b/testutil/testutil_test.go index 04045eb8..4ce8ac01 100644 --- a/testutil/testutil_test.go +++ b/testutil/testutil_test.go @@ -1,7 +1,7 @@ package testutil_test import ( - "github.com/chris-ramon/graphql-go/testutil" + "github.com/chris-ramon/graphql/testutil" "testing" ) diff --git a/types/definition.go b/types/definition.go index ad7b9e4e..7f8e6c7e 100644 --- a/types/definition.go +++ b/types/definition.go @@ -6,8 +6,8 @@ import ( "reflect" "regexp" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/ast" ) // These are all of the possible kinds of types. diff --git a/types/definition_test.go b/types/definition_test.go index 6c2b36b3..88bda225 100644 --- a/types/definition_test.go +++ b/types/definition_test.go @@ -5,8 +5,8 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" ) var blogImage = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ diff --git a/types/enum_type_test.go b/types/enum_type_test.go index 3d2e4967..507409d7 100644 --- a/types/enum_type_test.go +++ b/types/enum_type_test.go @@ -1,10 +1,10 @@ package types_test import ( - "github.com/chris-ramon/graphql-go" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/types/introspection.go b/types/introspection.go index 76261530..fd6e61e9 100644 --- a/types/introspection.go +++ b/types/introspection.go @@ -2,8 +2,8 @@ package types import ( "fmt" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/language/printer" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/printer" "math" "reflect" ) diff --git a/types/introspection_test.go b/types/introspection_test.go index edc14c94..7f2cdfb7 100644 --- a/types/introspection_test.go +++ b/types/introspection_test.go @@ -1,11 +1,11 @@ package types_test import ( - "github.com/chris-ramon/graphql-go" - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/location" - "github.com/chris-ramon/graphql-go/testutil" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/testutil" + "github.com/chris-ramon/graphql/types" "reflect" "testing" ) diff --git a/types/scalars.go b/types/scalars.go index 1122e591..b3574c15 100644 --- a/types/scalars.go +++ b/types/scalars.go @@ -4,7 +4,7 @@ import ( "fmt" "strconv" - "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql/language/ast" ) var ( diff --git a/types/types.go b/types/types.go index 9b50a897..98fb8394 100644 --- a/types/types.go +++ b/types/types.go @@ -1,7 +1,7 @@ package types import ( - "github.com/chris-ramon/graphql-go/errors" + "github.com/chris-ramon/graphql/errors" ) type Schema interface{} diff --git a/types/validation_test.go b/types/validation_test.go index d59bf455..645b0b98 100644 --- a/types/validation_test.go +++ b/types/validation_test.go @@ -3,8 +3,8 @@ package types_test import ( "testing" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/types" ) var someScalarType = types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ diff --git a/validator/validator.go b/validator/validator.go index 8da1c445..0c1ee128 100644 --- a/validator/validator.go +++ b/validator/validator.go @@ -1,9 +1,9 @@ package validator import ( - "github.com/chris-ramon/graphql-go/errors" - "github.com/chris-ramon/graphql-go/language/ast" - "github.com/chris-ramon/graphql-go/types" + "github.com/chris-ramon/graphql/errors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/types" ) type ValidationResult struct { From f832252c50e06b4dc48392977b9a8ca5675b04a9 Mon Sep 17 00:00:00 2001 From: Nathaniel Maman Date: Tue, 27 Oct 2015 15:03:56 +0200 Subject: [PATCH 2/6] rename gql to graphql --- executor/abstract_test.go | 8 ++++---- executor/executor.go | 2 +- graphql.go | 2 +- graphql_test.go | 2 +- types/enum_type_test.go | 4 ++-- types/introspection_test.go | 24 ++++++++++++------------ 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/executor/abstract_test.go b/executor/abstract_test.go index abd60c9e..93bfb20a 100644 --- a/executor/abstract_test.go +++ b/executor/abstract_test.go @@ -147,7 +147,7 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { resultChannel := make(chan *types.GraphQLResult) - go gql.Graphql(gql.GraphqlParams{ + go graphql.Graphql(graphql.GraphqlParams{ Schema: schema, RequestString: query, }, resultChannel) @@ -282,7 +282,7 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { resultChannel := make(chan *types.GraphQLResult) - go gql.Graphql(gql.GraphqlParams{ + go graphql.Graphql(graphql.GraphqlParams{ Schema: schema, RequestString: query, }, resultChannel) @@ -453,7 +453,7 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { resultChannel := make(chan *types.GraphQLResult) - go gql.Graphql(gql.GraphqlParams{ + go graphql.Graphql(graphql.GraphqlParams{ Schema: schema, RequestString: query, }, resultChannel) @@ -611,7 +611,7 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { resultChannel := make(chan *types.GraphQLResult) - go gql.Graphql(gql.GraphqlParams{ + go graphql.Graphql(graphql.GraphqlParams{ Schema: schema, RequestString: query, }, resultChannel) diff --git a/executor/executor.go b/executor/executor.go index dd65643d..18f09df7 100644 --- a/executor/executor.go +++ b/executor/executor.go @@ -703,7 +703,7 @@ func defaultResolveFn(p types.GQLFRParams) interface{} { } if sourceVal.Type().Kind() == reflect.Struct { // find field based on struct's json tag - // we could potentially create a custom `gql` tag, but its unnecessary at this point + // we could potentially create a custom `graphql` tag, but its unnecessary at this point // since graphql speaks to client in a json-like way anyway // so json tags are a good way to start with for i := 0; i < sourceVal.NumField(); i++ { diff --git a/graphql.go b/graphql.go index b904d903..6c5ce2ee 100644 --- a/graphql.go +++ b/graphql.go @@ -1,4 +1,4 @@ -package gql +package graphql import ( "github.com/chris-ramon/graphql/errors" diff --git a/graphql_test.go b/graphql_test.go index 3136a646..2ae18f1d 100644 --- a/graphql_test.go +++ b/graphql_test.go @@ -1,4 +1,4 @@ -package gql +package graphql import ( "reflect" diff --git a/types/enum_type_test.go b/types/enum_type_test.go index 507409d7..4e367ec0 100644 --- a/types/enum_type_test.go +++ b/types/enum_type_test.go @@ -99,14 +99,14 @@ var enumTypeTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ }) func executeEnumTypeTest(t *testing.T, query string) *types.GraphQLResult { - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: enumTypeTestSchema, RequestString: query, }) return result } func executeEnumTypeTestWithParams(t *testing.T, query string, params map[string]interface{}) *types.GraphQLResult { - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: enumTypeTestSchema, RequestString: query, VariableValues: params, diff --git a/types/introspection_test.go b/types/introspection_test.go index 7f2cdfb7..0c26d789 100644 --- a/types/introspection_test.go +++ b/types/introspection_test.go @@ -10,9 +10,9 @@ import ( "testing" ) -func graphql(t *testing.T, p gql.GraphqlParams) *types.GraphQLResult { +func g(t *testing.T, p graphql.GraphqlParams) *types.GraphQLResult { resultChannel := make(chan *types.GraphQLResult) - go gql.Graphql(p, resultChannel) + go graphql.Graphql(p, resultChannel) result := <-resultChannel return result } @@ -738,7 +738,7 @@ func TestIntrospection_ExecutesAnIntrospectionQuery(t *testing.T) { }, }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: emptySchema, RequestString: testutil.IntrospectionQuery, }) @@ -850,7 +850,7 @@ func TestIntrospection_ExecutesAnInputObject(t *testing.T) { }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: schema, RequestString: query, }) @@ -889,7 +889,7 @@ func TestIntrospection_SupportsThe__TypeRootField(t *testing.T) { }, }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: schema, RequestString: query, }) @@ -948,7 +948,7 @@ func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) { }, }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: schema, RequestString: query, }) @@ -1017,7 +1017,7 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForFields(t *testing }, }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: schema, RequestString: query, }) @@ -1092,7 +1092,7 @@ func TestIntrospection_IdentifiesDeprecatedEnumValues(t *testing.T) { }, }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: schema, RequestString: query, }) @@ -1181,7 +1181,7 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForEnumValues(t *tes }, }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: schema, RequestString: query, }) @@ -1223,7 +1223,7 @@ func TestIntrospection_FailsAsExpectedOnThe__TypeRootFieldWithoutAnArg(t *testin }, }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: schema, RequestString: query, }) @@ -1291,7 +1291,7 @@ mutation operations.`, }, }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: schema, RequestString: query, }) @@ -1369,7 +1369,7 @@ func TestIntrospection_ExposesDescriptionsOnEnums(t *testing.T) { }, }, } - result := graphql(t, gql.GraphqlParams{ + result := g(t, graphql.GraphqlParams{ Schema: schema, RequestString: query, }) From 1e388cf79c234cec068850c14ae1ccb002c6a68c Mon Sep 17 00:00:00 2001 From: Nathaniel Maman Date: Tue, 27 Oct 2015 15:57:15 +0200 Subject: [PATCH 3/6] rm GraphQL prefix and Type suffix from structs and interfaces --- errors/formatted.go | 24 +- errors/graphql.go | 8 +- errors/located.go | 4 +- errors/sortutil.go | 2 +- errors/syntax.go | 4 +- executor/abstract_test.go | 244 +++---- executor/directives_test.go | 50 +- executor/executor.go | 112 ++-- executor/executor_schema_test.go | 90 +-- executor/executor_test.go | 354 +++++----- executor/lists_test.go | 172 ++--- executor/mutations_test.go | 62 +- executor/nonnull_test.go | 176 ++--- executor/union_interface_test.go | 112 ++-- executor/values.go | 58 +- executor/variables_test.go | 220 +++---- graphql.go | 10 +- graphql_test.go | 26 +- language/ast/definitions.go | 2 +- language/ast/node.go | 12 +- language/ast/type_definitions.go | 176 +++-- language/ast/types.go | 2 +- language/kinds/kinds.go | 12 +- language/parser/parser.go | 26 +- language/parser/parser_test.go | 38 +- language/parser/schema_parser_test.go | 74 +-- language/printer/printer.go | 12 +- language/printer/schema_printer_test.go | 2 +- language/visitor/visitor.go | 12 +- testutil/testutil.go | 122 ++-- types/definition.go | 474 +++++++------- types/definition_test.go | 294 ++++----- types/directives.go | 26 +- types/enum_type_test.go | 112 ++-- types/introspection.go | 312 ++++----- types/introspection_test.go | 198 +++--- types/scalars.go | 10 +- types/scalars_serialization_test.go | 16 +- types/schema.go | 82 +-- types/types.go | 8 +- types/validation_test.go | 836 ++++++++++++------------ validator/validator.go | 4 +- 42 files changed, 2291 insertions(+), 2299 deletions(-) diff --git a/errors/formatted.go b/errors/formatted.go index 010b8795..d12b5a02 100644 --- a/errors/formatted.go +++ b/errors/formatted.go @@ -5,44 +5,44 @@ import ( "github.com/chris-ramon/graphql/language/location" ) -type GraphQLFormattedError struct { +type FormattedError struct { Message string Locations []location.SourceLocation } -func (g GraphQLFormattedError) Error() string { +func (g FormattedError) Error() string { return g.Message } -func NewGraphQLFormattedError(message string) GraphQLFormattedError { +func NewFormattedError(message string) FormattedError { err := errors.New(message) return FormatError(err) } -func FormatError(err error) GraphQLFormattedError { +func FormatError(err error) FormattedError { switch err := err.(type) { - case GraphQLFormattedError: + case FormattedError: return err - case *GraphQLError: - return GraphQLFormattedError{ + case *Error: + return FormattedError{ Message: err.Error(), Locations: err.Locations, } - case GraphQLError: - return GraphQLFormattedError{ + case Error: + return FormattedError{ Message: err.Error(), Locations: err.Locations, } default: - return GraphQLFormattedError{ + return FormattedError{ Message: err.Error(), Locations: []location.SourceLocation{}, } } } -func FormatErrors(errs ...error) []GraphQLFormattedError { - formattedErrors := []GraphQLFormattedError{} +func FormatErrors(errs ...error) []FormattedError { + formattedErrors := []FormattedError{} for _, err := range errs { formattedErrors = append(formattedErrors, FormatError(err)) } diff --git a/errors/graphql.go b/errors/graphql.go index 6dc98928..31dd64f9 100644 --- a/errors/graphql.go +++ b/errors/graphql.go @@ -7,7 +7,7 @@ import ( "github.com/chris-ramon/graphql/language/source" ) -type GraphQLError struct { +type Error struct { Message string Stack string Nodes []ast.Node @@ -17,11 +17,11 @@ type GraphQLError struct { } // implements Golang's built-in `error` interface -func (g GraphQLError) Error() string { +func (g Error) Error() string { return fmt.Sprintf("%v", g.Message) } -func NewGraphQLError(message string, nodes []ast.Node, stack string, source *source.Source, positions []int) *GraphQLError { +func NewError(message string, nodes []ast.Node, stack string, source *source.Source, positions []int) *Error { if stack == "" && message != "" { stack = message } @@ -47,7 +47,7 @@ func NewGraphQLError(message string, nodes []ast.Node, stack string, source *sou loc := location.GetLocation(source, pos) locations = append(locations, loc) } - return &GraphQLError{ + return &Error{ Message: message, Stack: stack, Nodes: nodes, diff --git a/errors/located.go b/errors/located.go index 590a52b8..273a29c9 100644 --- a/errors/located.go +++ b/errors/located.go @@ -4,7 +4,7 @@ import ( "github.com/chris-ramon/graphql/language/ast" ) -func NewLocatedError(err interface{}, nodes []ast.Node) *GraphQLError { +func NewLocatedError(err interface{}, nodes []ast.Node) *Error { message := "An unknown error occurred." if err, ok := err.(error); ok { message = err.Error() @@ -13,7 +13,7 @@ func NewLocatedError(err interface{}, nodes []ast.Node) *GraphQLError { message = err } stack := message - return NewGraphQLError( + return NewError( message, nodes, stack, diff --git a/errors/sortutil.go b/errors/sortutil.go index 2f17e75e..03b8133c 100644 --- a/errors/sortutil.go +++ b/errors/sortutil.go @@ -2,7 +2,7 @@ package graphqlerrors import "bytes" -type GQLFormattedErrorSlice []GraphQLFormattedError +type GQLFormattedErrorSlice []FormattedError func (errs GQLFormattedErrorSlice) Len() int { return len(errs) diff --git a/errors/syntax.go b/errors/syntax.go index c934c574..2c1fc548 100644 --- a/errors/syntax.go +++ b/errors/syntax.go @@ -9,9 +9,9 @@ import ( "github.com/chris-ramon/graphql/language/source" ) -func NewSyntaxError(s *source.Source, position int, description string) *GraphQLError { +func NewSyntaxError(s *source.Source, position int, description string) *Error { l := location.GetLocation(s, position) - return NewGraphQLError( + return NewError( fmt.Sprintf("Syntax Error %s (%d:%d) %s\n\n%s", s.Name, l.Line, l.Column, description, highlightSourceAtLocation(s, l)), []ast.Node{}, "", diff --git a/executor/abstract_test.go b/executor/abstract_test.go index 93bfb20a..26935583 100644 --- a/executor/abstract_test.go +++ b/executor/abstract_test.go @@ -26,28 +26,28 @@ type testHuman struct { func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { - petType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + petType := types.NewInterface(types.InterfaceConfig{ Name: "Pet", - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, }, }, }) // ie declare that Dog belongs to Pet interface - _ = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _ = types.NewObject(types.ObjectConfig{ Name: "Dog", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ petType, }, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testDog) return ok }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Name @@ -55,8 +55,8 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { return nil }, }, - "woofs": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "woofs": &types.FieldConfig{ + Type: types.Boolean, Resolve: func(p types.GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Woofs @@ -67,18 +67,18 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { }, }) // ie declare that Cat belongs to Pet interface - _ = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _ = types.NewObject(types.ObjectConfig{ Name: "Cat", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ petType, }, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testCat) return ok }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Name @@ -86,8 +86,8 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { return nil }, }, - "meows": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "meows": &types.FieldConfig{ + Type: types.Boolean, Resolve: func(p types.GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Meows @@ -97,12 +97,12 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "pets": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(petType), + Fields: types.FieldConfigMap{ + "pets": &types.FieldConfig{ + Type: types.NewList(petType), Resolve: func(p types.GQLFRParams) interface{} { return []interface{}{ &testDog{"Odie", true}, @@ -129,7 +129,7 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { } }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "pets": []interface{}{ map[string]interface{}{ @@ -145,9 +145,9 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { Errors: nil, } - resultChannel := make(chan *types.GraphQLResult) + resultChannel := make(chan *types.Result) - go graphql.Graphql(graphql.GraphqlParams{ + go graphql.Graphql(graphql.Params{ Schema: schema, RequestString: query, }, resultChannel) @@ -162,15 +162,15 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { - dogType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + dogType := types.NewObject(types.ObjectConfig{ Name: "Dog", - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testDog) return ok }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Name @@ -178,8 +178,8 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { return nil }, }, - "woofs": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "woofs": &types.FieldConfig{ + Type: types.Boolean, Resolve: func(p types.GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Woofs @@ -189,15 +189,15 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { }, }, }) - catType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + catType := types.NewObject(types.ObjectConfig{ Name: "Cat", - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testCat) return ok }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Name @@ -205,8 +205,8 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { return nil }, }, - "meows": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "meows": &types.FieldConfig{ + Type: types.Boolean, Resolve: func(p types.GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Meows @@ -217,12 +217,12 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { }, }) // ie declare Pet has Dot and Cat object types - petType := types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + petType := types.NewUnion(types.UnionConfig{ Name: "Pet", - Types: []*types.GraphQLObjectType{ + Types: []*types.Object{ dogType, catType, }, - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { if _, ok := value.(*testCat); ok { return catType } @@ -232,12 +232,12 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { return nil }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "pets": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(petType), + Fields: types.FieldConfigMap{ + "pets": &types.FieldConfig{ + Type: types.NewList(petType), Resolve: func(p types.GQLFRParams) interface{} { return []interface{}{ &testDog{"Odie", true}, @@ -264,7 +264,7 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { } }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "pets": []interface{}{ map[string]interface{}{ @@ -280,9 +280,9 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { Errors: nil, } - resultChannel := make(chan *types.GraphQLResult) + resultChannel := make(chan *types.Result) - go graphql.Graphql(graphql.GraphqlParams{ + go graphql.Graphql(graphql.Params{ Schema: schema, RequestString: query, }, resultChannel) @@ -298,17 +298,17 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { - var dogType *types.GraphQLObjectType - var catType *types.GraphQLObjectType - var humanType *types.GraphQLObjectType - petType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + var dogType *types.Object + var catType *types.Object + var humanType *types.Object + petType := types.NewInterface(types.InterfaceConfig{ Name: "Pet", - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, }, }, - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { if _, ok := value.(*testCat); ok { return catType } @@ -322,11 +322,11 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { }, }) - humanType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + humanType = types.NewObject(types.ObjectConfig{ Name: "Human", - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if human, ok := p.Source.(*testHuman); ok { return human.Name @@ -336,18 +336,18 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { }, }, }) - dogType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + dogType = types.NewObject(types.ObjectConfig{ Name: "Dog", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ petType, }, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testDog) return ok }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Name @@ -355,8 +355,8 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { return nil }, }, - "woofs": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "woofs": &types.FieldConfig{ + Type: types.Boolean, Resolve: func(p types.GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Woofs @@ -366,18 +366,18 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { }, }, }) - catType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + catType = types.NewObject(types.ObjectConfig{ Name: "Cat", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ petType, }, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testCat) return ok }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Name @@ -385,8 +385,8 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { return nil }, }, - "meows": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "meows": &types.FieldConfig{ + Type: types.Boolean, Resolve: func(p types.GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Meows @@ -396,12 +396,12 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "pets": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(petType), + Fields: types.FieldConfigMap{ + "pets": &types.FieldConfig{ + Type: types.NewList(petType), Resolve: func(p types.GQLFRParams) interface{} { return []interface{}{ &testDog{"Odie", true}, @@ -429,7 +429,7 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { } }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "pets": []interface{}{ map[string]interface{}{ @@ -443,17 +443,17 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { nil, }, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Runtime Object type "Human" is not a possible type for "Pet".`, Locations: []location.SourceLocation{}, }, }, } - resultChannel := make(chan *types.GraphQLResult) + resultChannel := make(chan *types.Result) - go graphql.Graphql(graphql.GraphqlParams{ + go graphql.Graphql(graphql.Params{ Schema: schema, RequestString: query, }, resultChannel) @@ -468,11 +468,11 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { - humanType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + humanType := types.NewObject(types.ObjectConfig{ Name: "Human", - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if human, ok := p.Source.(*testHuman); ok { return human.Name @@ -482,15 +482,15 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { }, }, }) - dogType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + dogType := types.NewObject(types.ObjectConfig{ Name: "Dog", - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testDog) return ok }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Name @@ -498,8 +498,8 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { return nil }, }, - "woofs": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "woofs": &types.FieldConfig{ + Type: types.Boolean, Resolve: func(p types.GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Woofs @@ -509,15 +509,15 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { }, }, }) - catType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + catType := types.NewObject(types.ObjectConfig{ Name: "Cat", - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testCat) return ok }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Name @@ -525,8 +525,8 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { return nil }, }, - "meows": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "meows": &types.FieldConfig{ + Type: types.Boolean, Resolve: func(p types.GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Meows @@ -536,12 +536,12 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { }, }, }) - petType := types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + petType := types.NewUnion(types.UnionConfig{ Name: "Pet", - Types: []*types.GraphQLObjectType{ + Types: []*types.Object{ dogType, catType, }, - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { if _, ok := value.(*testCat); ok { return catType } @@ -554,12 +554,12 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { return nil }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "pets": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(petType), + Fields: types.FieldConfigMap{ + "pets": &types.FieldConfig{ + Type: types.NewList(petType), Resolve: func(p types.GQLFRParams) interface{} { return []interface{}{ &testDog{"Odie", true}, @@ -587,7 +587,7 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { } }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "pets": []interface{}{ map[string]interface{}{ @@ -601,17 +601,17 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { nil, }, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Runtime Object type "Human" is not a possible type for "Pet".`, Locations: []location.SourceLocation{}, }, }, } - resultChannel := make(chan *types.GraphQLResult) + resultChannel := make(chan *types.Result) - go graphql.Graphql(graphql.GraphqlParams{ + go graphql.Graphql(graphql.Params{ Schema: schema, RequestString: query, }, resultChannel) diff --git a/executor/directives_test.go b/executor/directives_test.go index 8a8acf0d..d416f855 100644 --- a/executor/directives_test.go +++ b/executor/directives_test.go @@ -8,15 +8,15 @@ import ( "testing" ) -var directivesTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var directivesTestSchema, _ = types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "TestType", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, - "b": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "b": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -27,7 +27,7 @@ var directivesTestData map[string]interface{} = map[string]interface{}{ "b": func() interface{} { return "b" }, } -func executeDirectivesTestQuery(t *testing.T, doc string) *types.GraphQLResult { +func executeDirectivesTestQuery(t *testing.T, doc string) *types.Result { ast := testutil.Parse(t, doc) ep := executor.ExecuteParams{ Schema: directivesTestSchema, @@ -39,7 +39,7 @@ func executeDirectivesTestQuery(t *testing.T, doc string) *types.GraphQLResult { func TestDirectivesWorksWithoutDirectives(t *testing.T) { query := `{ a, b }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -56,7 +56,7 @@ func TestDirectivesWorksWithoutDirectives(t *testing.T) { func TestDirectivesWorksOnScalarsIfTrueIncludesScalar(t *testing.T) { query := `{ a, b @include(if: true) }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -73,7 +73,7 @@ func TestDirectivesWorksOnScalarsIfTrueIncludesScalar(t *testing.T) { func TestDirectivesWorksOnScalarsIfFalseOmitsOnScalar(t *testing.T) { query := `{ a, b @include(if: false) }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", }, @@ -89,7 +89,7 @@ func TestDirectivesWorksOnScalarsIfFalseOmitsOnScalar(t *testing.T) { func TestDirectivesWorksOnScalarsUnlessFalseIncludesScalar(t *testing.T) { query := `{ a, b @skip(if: false) }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -106,7 +106,7 @@ func TestDirectivesWorksOnScalarsUnlessFalseIncludesScalar(t *testing.T) { func TestDirectivesWorksOnScalarsUnlessTrueOmitsScalar(t *testing.T) { query := `{ a, b @skip(if: true) }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", }, @@ -130,7 +130,7 @@ func TestDirectivesWorksOnFragmentSpreadsIfFalseOmitsFragmentSpread(t *testing.T b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", }, @@ -154,7 +154,7 @@ func TestDirectivesWorksOnFragmentSpreadsIfTrueIncludesFragmentSpread(t *testing b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -179,7 +179,7 @@ func TestDirectivesWorksOnFragmentSpreadsUnlessFalseIncludesFragmentSpread(t *te b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -204,7 +204,7 @@ func TestDirectivesWorksOnFragmentSpreadsUnlessTrueOmitsFragmentSpread(t *testin b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", }, @@ -230,7 +230,7 @@ func TestDirectivesWorksOnInlineFragmentIfFalseOmitsInlineFragment(t *testing.T) b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", }, @@ -256,7 +256,7 @@ func TestDirectivesWorksOnInlineFragmentIfTrueIncludesInlineFragment(t *testing. b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -283,7 +283,7 @@ func TestDirectivesWorksOnInlineFragmentUnlessFalseIncludesInlineFragment(t *tes b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -310,7 +310,7 @@ func TestDirectivesWorksOnInlineFragmentUnlessTrueIncludesInlineFragment(t *test b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", }, @@ -334,7 +334,7 @@ func TestDirectivesWorksOnFragmentIfFalseOmitsFragment(t *testing.T) { b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", }, @@ -358,7 +358,7 @@ func TestDirectivesWorksOnFragmentIfTrueIncludesFragment(t *testing.T) { b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -383,7 +383,7 @@ func TestDirectivesWorksOnFragmentUnlessFalseIncludesFragment(t *testing.T) { b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -408,7 +408,7 @@ func TestDirectivesWorksOnFragmentUnlessTrueOmitsFragment(t *testing.T) { b } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", }, diff --git a/executor/executor.go b/executor/executor.go index 18f09df7..72f6d024 100644 --- a/executor/executor.go +++ b/executor/executor.go @@ -11,16 +11,16 @@ import ( ) type ExecuteParams struct { - Schema types.GraphQLSchema + Schema types.Schema Root interface{} AST *ast.Document OperationName string Args map[string]interface{} } -func Execute(p ExecuteParams, resultChan chan *types.GraphQLResult) { - var errors []graphqlerrors.GraphQLFormattedError - var result types.GraphQLResult +func Execute(p ExecuteParams, resultChan chan *types.Result) { + var errors []graphqlerrors.FormattedError + var result types.Result params := BuildExecutionCtxParams{ Schema: p.Schema, Root: p.Root, @@ -55,22 +55,22 @@ func Execute(p ExecuteParams, resultChan chan *types.GraphQLResult) { } type BuildExecutionCtxParams struct { - Schema types.GraphQLSchema + Schema types.Schema Root interface{} AST *ast.Document OperationName string Args map[string]interface{} - Errors []graphqlerrors.GraphQLFormattedError - Result *types.GraphQLResult - ResultChan chan *types.GraphQLResult + Errors []graphqlerrors.FormattedError + Result *types.Result + ResultChan chan *types.Result } type ExecutionContext struct { - Schema types.GraphQLSchema + Schema types.Schema Fragments map[string]ast.Definition Root interface{} Operation ast.Definition VariableValues map[string]interface{} - Errors []graphqlerrors.GraphQLFormattedError + Errors []graphqlerrors.FormattedError } func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { @@ -92,7 +92,7 @@ func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { } fragments[key] = stm default: - err := graphqlerrors.NewGraphQLFormattedError( + err := graphqlerrors.NewFormattedError( fmt.Sprintf("GraphQL cannot execute a request containing a %v", statement.GetKind()), ) p.Result.Errors = append(p.Result.Errors, err) @@ -101,7 +101,7 @@ func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { } } if (p.OperationName == "") && (len(operations) != 1) { - err := graphqlerrors.NewGraphQLFormattedError("Must provide operation name if query contains multiple operations.") + err := graphqlerrors.NewFormattedError("Must provide operation name if query contains multiple operations.") p.Result.Errors = append(p.Result.Errors, err) p.ResultChan <- p.Result return eCtx @@ -116,7 +116,7 @@ func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { } operation, found := operations[opName] if !found { - err := graphqlerrors.NewGraphQLFormattedError(fmt.Sprintf(`Unknown operation named "%v".`, opName)) + err := graphqlerrors.NewFormattedError(fmt.Sprintf(`Unknown operation named "%v".`, opName)) p.Result.Errors = append(p.Result.Errors, err) p.ResultChan <- p.Result return eCtx @@ -143,8 +143,8 @@ type ExecuteOperationParams struct { Operation ast.Definition } -func executeOperation(p ExecuteOperationParams, resultChan chan *types.GraphQLResult) { - var results types.GraphQLResult +func executeOperation(p ExecuteOperationParams, resultChan chan *types.Result) { + var results types.Result operationType := getOperationRootType(p.ExecutionContext.Schema, p.Operation, resultChan) collectFieldsParams := CollectFieldsParams{ @@ -169,10 +169,10 @@ func executeOperation(p ExecuteOperationParams, resultChan chan *types.GraphQLRe } // Extracts the root type of the operation from the schema. -func getOperationRootType(schema types.GraphQLSchema, operation ast.Definition, r chan *types.GraphQLResult) (objType *types.GraphQLObjectType) { +func getOperationRootType(schema types.Schema, operation ast.Definition, r chan *types.Result) (objType *types.Object) { if operation == nil { - var result types.GraphQLResult - err := graphqlerrors.NewGraphQLFormattedError("Can only execute queries and mutations") + var result types.Result + err := graphqlerrors.NewFormattedError("Can only execute queries and mutations") result.Errors = append(result.Errors, err) r <- &result return objType @@ -183,16 +183,16 @@ func getOperationRootType(schema types.GraphQLSchema, operation ast.Definition, case "mutation": mutationType := schema.GetMutationType() if mutationType.Name == "" { - var result types.GraphQLResult - err := graphqlerrors.NewGraphQLFormattedError("Schema is not configured for mutations") + var result types.Result + err := graphqlerrors.NewFormattedError("Schema is not configured for mutations") result.Errors = append(result.Errors, err) r <- &result return objType } return mutationType default: - var result types.GraphQLResult - err := graphqlerrors.NewGraphQLFormattedError("Can only execute queries and mutations") + var result types.Result + err := graphqlerrors.NewFormattedError("Can only execute queries and mutations") result.Errors = append(result.Errors, err) r <- &result return objType @@ -201,20 +201,20 @@ func getOperationRootType(schema types.GraphQLSchema, operation ast.Definition, type ExecuteFieldsParams struct { ExecutionContext *ExecutionContext - ParentType *types.GraphQLObjectType + ParentType *types.Object Source interface{} Fields map[string][]*ast.Field } // Implements the "Evaluating selection sets" section of the spec for "write" mode. -func executeFieldsSerially(p ExecuteFieldsParams, resultChan chan *types.GraphQLResult) { +func executeFieldsSerially(p ExecuteFieldsParams, resultChan chan *types.Result) { if p.Source == nil { p.Source = map[string]interface{}{} } if p.Fields == nil { p.Fields = map[string][]*ast.Field{} } - var result types.GraphQLResult + var result types.Result finalResults := map[string]interface{}{} for responseName, fieldASTs := range p.Fields { @@ -230,7 +230,7 @@ func executeFieldsSerially(p ExecuteFieldsParams, resultChan chan *types.GraphQL } // Implements the "Evaluating selection sets" section of the spec for "read" mode. -func executeFields(p ExecuteFieldsParams) (result types.GraphQLResult) { +func executeFields(p ExecuteFieldsParams) (result types.Result) { if p.Source == nil { p.Source = map[string]interface{}{} } @@ -254,7 +254,7 @@ func executeFields(p ExecuteFieldsParams) (result types.GraphQLResult) { type CollectFieldsParams struct { ExeContext *ExecutionContext - OperationType *types.GraphQLObjectType + OperationType *types.Object SelectionSet *ast.SelectionSet Fields map[string][]*ast.Field VisitedFragmentNames map[string]bool @@ -345,14 +345,14 @@ func shouldIncludeNode(eCtx *ExecutionContext, directives []*ast.Directive) bool if directive == nil || directive.Name == nil { continue } - if directive.Name.Value == types.GraphQLSkipDirective.Name { + if directive.Name.Value == types.SkipDirective.Name { skipAST = directive break } } if skipAST != nil { argValues, err := getArgumentValues( - types.GraphQLSkipDirective.Args, + types.SkipDirective.Args, skipAST.Arguments, eCtx.VariableValues, ) @@ -370,14 +370,14 @@ func shouldIncludeNode(eCtx *ExecutionContext, directives []*ast.Directive) bool if directive == nil || directive.Name == nil { continue } - if directive.Name.Value == types.GraphQLIncludeDirective.Name { + if directive.Name.Value == types.IncludeDirective.Name { includeAST = directive break } } if includeAST != nil { argValues, err := getArgumentValues( - types.GraphQLIncludeDirective.Args, + types.IncludeDirective.Args, includeAST.Arguments, eCtx.VariableValues, ) @@ -395,7 +395,7 @@ func shouldIncludeNode(eCtx *ExecutionContext, directives []*ast.Directive) bool } // Determines if a fragment is applicable to the given type. -func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment ast.Node, ttype *types.GraphQLObjectType) bool { +func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment ast.Node, ttype *types.Object) bool { switch fragment := fragment.(type) { case *ast.FragmentDefinition: @@ -407,7 +407,7 @@ func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment ast.Node, ttype return true } - if conditionalType, ok := conditionalType.(types.GraphQLAbstractType); ok { + if conditionalType, ok := conditionalType.(types.Abstract); ok { return conditionalType.IsPossibleType(ttype) } case *ast.InlineFragment: @@ -419,7 +419,7 @@ func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment ast.Node, ttype return true } - if conditionalType, ok := conditionalType.(types.GraphQLAbstractType); ok { + if conditionalType, ok := conditionalType.(types.Abstract); ok { return conditionalType.IsPossibleType(ttype) } } @@ -450,9 +450,9 @@ type resolveFieldResultState struct { * then calls completeValue to complete promises, serialize scalars, or execute * the sub-selection-set for objects. */ -func resolveField(eCtx *ExecutionContext, parentType *types.GraphQLObjectType, source interface{}, fieldASTs []*ast.Field) (result interface{}, resultState resolveFieldResultState) { +func resolveField(eCtx *ExecutionContext, parentType *types.Object, source interface{}, fieldASTs []*ast.Field) (result interface{}, resultState resolveFieldResultState) { // catch panic from resolveFn - var returnType types.GraphQLOutputType + var returnType types.Output defer func() (interface{}, resolveFieldResultState) { if r := recover(); r != nil { @@ -467,7 +467,7 @@ func resolveField(eCtx *ExecutionContext, parentType *types.GraphQLObjectType, s err = graphqlerrors.FormatError(r) } // send panic upstream - if _, ok := returnType.(*types.GraphQLNonNull); ok { + if _, ok := returnType.(*types.NonNull); ok { panic(graphqlerrors.FormatError(err)) } eCtx.Errors = append(eCtx.Errors, graphqlerrors.FormatError(err)) @@ -500,7 +500,7 @@ func resolveField(eCtx *ExecutionContext, parentType *types.GraphQLObjectType, s // The resolve function's optional third argument is a collection of // information about the current execution state. - info := types.GraphQLResolveInfo{ + info := types.ResolveInfo{ FieldName: fieldName, FieldASTs: fieldASTs, ReturnType: returnType, @@ -513,7 +513,7 @@ func resolveField(eCtx *ExecutionContext, parentType *types.GraphQLObjectType, s } // TODO: If an error occurs while calling the field `resolve` function, ensure that - // it is wrapped as a GraphQLError with locations. Log this error and return + // it is wrapped as a Error with locations. Log this error and return // null if allowed, otherwise throw the error so the parent field can handle // it. result = resolveFn(types.GQLFRParams{ @@ -526,15 +526,15 @@ func resolveField(eCtx *ExecutionContext, parentType *types.GraphQLObjectType, s return completed, resultState } -func completeValueCatchingError(eCtx *ExecutionContext, returnType types.GraphQLType, fieldASTs []*ast.Field, info types.GraphQLResolveInfo, result interface{}) (completed interface{}) { +func completeValueCatchingError(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*ast.Field, info types.ResolveInfo, result interface{}) (completed interface{}) { // catch panic defer func() interface{} { if r := recover(); r != nil { //send panic upstream - if _, ok := returnType.(*types.GraphQLNonNull); ok { + if _, ok := returnType.(*types.NonNull); ok { panic(r) } - if err, ok := r.(graphqlerrors.GraphQLFormattedError); ok { + if err, ok := r.(graphqlerrors.FormattedError); ok { eCtx.Errors = append(eCtx.Errors, err) } return completed @@ -542,7 +542,7 @@ func completeValueCatchingError(eCtx *ExecutionContext, returnType types.GraphQL return completed }() - if returnType, ok := returnType.(*types.GraphQLNonNull); ok { + if returnType, ok := returnType.(*types.NonNull); ok { completed := completeValue(eCtx, returnType, fieldASTs, info, result) return completed } @@ -552,13 +552,13 @@ func completeValueCatchingError(eCtx *ExecutionContext, returnType types.GraphQL if propertyFn, ok := completed.(func() interface{}); ok { return propertyFn() } - err := graphqlerrors.NewGraphQLFormattedError("Error resolving func. Expected `func() interface{}` signature") + err := graphqlerrors.NewFormattedError("Error resolving func. Expected `func() interface{}` signature") panic(graphqlerrors.FormatError(err)) } return completed } -func completeValue(eCtx *ExecutionContext, returnType types.GraphQLType, fieldASTs []*ast.Field, info types.GraphQLResolveInfo, result interface{}) interface{} { +func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*ast.Field, info types.ResolveInfo, result interface{}) interface{} { // TODO: explore resolving go-routines in completeValue @@ -567,11 +567,11 @@ func completeValue(eCtx *ExecutionContext, returnType types.GraphQLType, fieldAS if propertyFn, ok := result.(func() interface{}); ok { return propertyFn() } - err := graphqlerrors.NewGraphQLFormattedError("Error resolving func. Expected `func() interface{}` signature") + err := graphqlerrors.NewFormattedError("Error resolving func. Expected `func() interface{}` signature") panic(graphqlerrors.FormatError(err)) } - if returnType, ok := returnType.(*types.GraphQLNonNull); ok { + if returnType, ok := returnType.(*types.NonNull); ok { completed := completeValue(eCtx, returnType.OfType, fieldASTs, info, result) if completed == nil { err := graphqlerrors.NewLocatedError( @@ -588,7 +588,7 @@ func completeValue(eCtx *ExecutionContext, returnType types.GraphQLType, fieldAS } // If field type is List, complete each item in the list with the inner type - if returnType, ok := returnType.(*types.GraphQLList); ok { + if returnType, ok := returnType.(*types.List); ok { resultVal := reflect.ValueOf(result) err := invariant( @@ -611,7 +611,7 @@ func completeValue(eCtx *ExecutionContext, returnType types.GraphQLType, fieldAS // If field type is Scalar or Enum, serialize to a valid value, returning // null if serialization is not possible. - if returnType, ok := returnType.(*types.GraphQLScalarType); ok { + if returnType, ok := returnType.(*types.Scalar); ok { err := invariant(returnType.Serialize != nil, "Missing serialize method on type") if err != nil { panic(graphqlerrors.FormatError(err)) @@ -622,7 +622,7 @@ func completeValue(eCtx *ExecutionContext, returnType types.GraphQLType, fieldAS } return serializedResult } - if returnType, ok := returnType.(*types.GraphQLEnumType); ok { + if returnType, ok := returnType.(*types.Enum); ok { err := invariant(returnType.Serialize != nil, "Missing serialize method on type") if err != nil { panic(graphqlerrors.FormatError(err)) @@ -635,14 +635,14 @@ func completeValue(eCtx *ExecutionContext, returnType types.GraphQLType, fieldAS } // Field type must be Object, Interface or Union and expect sub-selections. - var objectType *types.GraphQLObjectType + var objectType *types.Object switch returnType := returnType.(type) { - case *types.GraphQLObjectType: + case *types.Object: objectType = returnType - case types.GraphQLAbstractType: + case types.Abstract: objectType = returnType.GetObjectType(result, info) if objectType != nil && !returnType.IsPossibleType(objectType) { - panic(graphqlerrors.NewGraphQLFormattedError( + panic(graphqlerrors.NewFormattedError( fmt.Sprintf(`Runtime Object type "%v" is not a possible type `+ `for "%v".`, objectType, returnType), )) @@ -656,7 +656,7 @@ func completeValue(eCtx *ExecutionContext, returnType types.GraphQLType, fieldAS // current result. If isTypeOf returns false, then raise an error rather // than continuing execution. if objectType.IsTypeOf != nil && !objectType.IsTypeOf(result, info) { - panic(graphqlerrors.NewGraphQLFormattedError( + panic(graphqlerrors.NewFormattedError( fmt.Sprintf(`Expected value of type "%v" but got: %T.`, objectType, result), )) } @@ -754,7 +754,7 @@ func defaultResolveFn(p types.GQLFRParams) interface{} { * added to the query type, but that would require mutating type * definitions, which would cause issues. */ -func getFieldDef(schema types.GraphQLSchema, parentType *types.GraphQLObjectType, fieldName string) *types.GraphQLFieldDefinition { +func getFieldDef(schema types.Schema, parentType *types.Object, fieldName string) *types.FieldDefinition { if parentType == nil { return nil diff --git a/executor/executor_schema_test.go b/executor/executor_schema_test.go index 96dafb3c..9aa78e36 100644 --- a/executor/executor_schema_test.go +++ b/executor/executor_schema_test.go @@ -73,37 +73,37 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { RecentArticle: article("1"), } - blogImage := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + blogImage := types.NewObject(types.ObjectConfig{ Name: "Image", - Fields: types.GraphQLFieldConfigMap{ - "url": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "url": &types.FieldConfig{ + Type: types.String, }, - "width": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, + "width": &types.FieldConfig{ + Type: types.Int, }, - "height": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, + "height": &types.FieldConfig{ + Type: types.Int, }, }, }) - blogAuthor := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + blogAuthor := types.NewObject(types.ObjectConfig{ Name: "Author", - Fields: types.GraphQLFieldConfigMap{ - "id": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "id": &types.FieldConfig{ + Type: types.String, }, - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "name": &types.FieldConfig{ + Type: types.String, }, - "pic": &types.GraphQLFieldConfig{ + "pic": &types.FieldConfig{ Type: blogImage, - Args: types.GraphQLFieldConfigArgumentMap{ - "width": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + Args: types.FieldConfigArgument{ + "width": &types.ArgumentConfig{ + Type: types.Int, }, - "height": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + "height": &types.ArgumentConfig{ + Type: types.Int, }, }, Resolve: func(p types.GQLFRParams) interface{} { @@ -115,45 +115,45 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { return nil }, }, - "recentArticle": &types.GraphQLFieldConfig{}, + "recentArticle": &types.FieldConfig{}, }, }) - blogArticle := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + blogArticle := types.NewObject(types.ObjectConfig{ Name: "Article", - Fields: types.GraphQLFieldConfigMap{ - "id": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(types.GraphQLString), + Fields: types.FieldConfigMap{ + "id": &types.FieldConfig{ + Type: types.NewNonNull(types.String), }, - "isPublished": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "isPublished": &types.FieldConfig{ + Type: types.Boolean, }, - "author": &types.GraphQLFieldConfig{ + "author": &types.FieldConfig{ Type: blogAuthor, }, - "title": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "title": &types.FieldConfig{ + Type: types.String, }, - "body": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "body": &types.FieldConfig{ + Type: types.String, }, - "keywords": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(types.GraphQLString), + "keywords": &types.FieldConfig{ + Type: types.NewList(types.String), }, }, }) - blogAuthor.AddFieldConfig("recentArticle", &types.GraphQLFieldConfig{ + blogAuthor.AddFieldConfig("recentArticle", &types.FieldConfig{ Type: blogArticle, }) - blogQuery := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + blogQuery := types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "article": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "article": &types.FieldConfig{ Type: blogArticle, - Args: types.GraphQLFieldConfigArgumentMap{ - "id": &types.GraphQLArgumentConfig{ - Type: types.GraphQLID, + Args: types.FieldConfigArgument{ + "id": &types.ArgumentConfig{ + Type: types.ID, }, }, Resolve: func(p types.GQLFRParams) interface{} { @@ -161,8 +161,8 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { return article(id) }, }, - "feed": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(blogArticle), + "feed": &types.FieldConfig{ + Type: types.NewList(blogArticle), Resolve: func(p types.GQLFRParams) interface{} { return []*testArticle{ article(1), @@ -181,7 +181,7 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { }, }) - blogSchema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + blogSchema, err := types.NewSchema(types.SchemaConfig{ Query: blogQuery, }) if err != nil { @@ -222,7 +222,7 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "article": map[string]interface{}{ "title": "My Article 1", diff --git a/executor/executor_test.go b/executor/executor_test.go index d0e28c75..aedb98d8 100644 --- a/executor/executor_test.go +++ b/executor/executor_test.go @@ -67,7 +67,7 @@ func TestExecutesArbitraryCode(t *testing.T) { } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "b": "Banana", "x": "Cookie", @@ -116,67 +116,67 @@ func TestExecutesArbitraryCode(t *testing.T) { } return picResolver(sizeArg) } - dataType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + dataType := types.NewObject(types.ObjectConfig{ Name: "DataType", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, - "b": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "b": &types.FieldConfig{ + Type: types.String, }, - "c": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "c": &types.FieldConfig{ + Type: types.String, }, - "d": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "d": &types.FieldConfig{ + Type: types.String, }, - "e": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "e": &types.FieldConfig{ + Type: types.String, }, - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "f": &types.FieldConfig{ + Type: types.String, }, - "pic": &types.GraphQLFieldConfig{ - Args: types.GraphQLFieldConfigArgumentMap{ - "size": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + "pic": &types.FieldConfig{ + Args: types.FieldConfigArgument{ + "size": &types.ArgumentConfig{ + Type: types.Int, }, }, - Type: types.GraphQLString, + Type: types.String, Resolve: picResolverFn, }, }, }) - deepDataType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + deepDataType := types.NewObject(types.ObjectConfig{ Name: "DeepDataType", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, - "b": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "b": &types.FieldConfig{ + Type: types.String, }, - "c": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(types.GraphQLString), + "c": &types.FieldConfig{ + Type: types.NewList(types.String), }, - "deeper": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(dataType), + "deeper": &types.FieldConfig{ + Type: types.NewList(dataType), }, }, }) - // Exploring a way to have a GraphQLObjectType within itself + // Exploring a way to have a Object within itself // in this case DataType has DeepDataType has DataType - dataType.AddFieldConfig("deep", &types.GraphQLFieldConfig{ + dataType.AddFieldConfig("deep", &types.FieldConfig{ Type: deepDataType, }) // in this case DataType has DataType - dataType.AddFieldConfig("promise", &types.GraphQLFieldConfig{ + dataType.AddFieldConfig("promise", &types.FieldConfig{ Type: dataType, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: dataType, }) if err != nil { @@ -223,7 +223,7 @@ func TestMergesParallelFragments(t *testing.T) { } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "Apple", "b": "Banana", @@ -239,30 +239,30 @@ func TestMergesParallelFragments(t *testing.T) { }, } - typeObjectType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + typeObjectType := types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { return "Apple" }, }, - "b": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "b": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { return "Banana" }, }, - "c": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "c": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { return "Cherry" }, }, }, }) - deepTypeFieldConfig := &types.GraphQLFieldConfig{ + deepTypeFieldConfig := &types.FieldConfig{ Type: typeObjectType, Resolve: func(p types.GQLFRParams) interface{} { return p.Source @@ -270,7 +270,7 @@ func TestMergesParallelFragments(t *testing.T) { } typeObjectType.AddFieldConfig("deep", deepTypeFieldConfig) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: typeObjectType, }) if err != nil { @@ -306,12 +306,12 @@ func TestThreadsContextCorrectly(t *testing.T) { var resolvedContext map[string]interface{} - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { resolvedContext = p.Source.(map[string]interface{}) return resolvedContext @@ -354,20 +354,20 @@ func TestCorrectlyThreadsArguments(t *testing.T) { var resolvedArgs map[string]interface{} - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "b": &types.GraphQLFieldConfig{ - Args: types.GraphQLFieldConfigArgumentMap{ - "numArg": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + Fields: types.FieldConfigMap{ + "b": &types.FieldConfig{ + Args: types.FieldConfigArgument{ + "numArg": &types.ArgumentConfig{ + Type: types.Int, }, - "stringArg": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + "stringArg": &types.ArgumentConfig{ + Type: types.String, }, }, - Type: types.GraphQLString, + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { resolvedArgs = p.Args return resolvedArgs @@ -415,8 +415,8 @@ func TestNullsOutErrorSubtrees(t *testing.T) { "sync": "sync", "syncError": nil, } - expectedErrors := []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + expectedErrors := []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Error getting syncError", Locations: []location.SourceLocation{ location.SourceLocation{ @@ -434,15 +434,15 @@ func TestNullsOutErrorSubtrees(t *testing.T) { panic("Error getting syncError") }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "sync": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "sync": &types.FieldConfig{ + Type: types.String, }, - "syncError": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "syncError": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -479,18 +479,18 @@ func TestUsesTheInlineOperationIfNoOperationIsProvided(t *testing.T) { "a": "b", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "b", }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -524,18 +524,18 @@ func TestUsesTheOnlyOperationIfNoOperationIsProvided(t *testing.T) { "a": "b", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "b", }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -569,19 +569,19 @@ func TestThrowsIfNoOperationIsProvidedWithMultipleOperations(t *testing.T) { "a": "b", } - expectedErrors := []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + expectedErrors := []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Must provide operation name if query contains multiple operations.", Locations: []location.SourceLocation{}, }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -619,26 +619,26 @@ func TestUsesTheQuerySchemaForQueries(t *testing.T) { "c": "d", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "b", }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Q", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, }, }), - Mutation: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + Mutation: types.NewObject(types.ObjectConfig{ Name: "M", - Fields: types.GraphQLFieldConfigMap{ - "c": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "c": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -674,26 +674,26 @@ func TestUsesTheMutationSchemaForQueries(t *testing.T) { "c": "d", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "c": "d", }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Q", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, }, }), - Mutation: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + Mutation: types.NewObject(types.ObjectConfig{ Name: "M", - Fields: types.GraphQLFieldConfigMap{ - "c": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "c": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -740,7 +740,7 @@ func TestCorrectFieldOrderingDespiteExecutionOrder(t *testing.T) { "e": func() interface{} { return "e" }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -750,24 +750,24 @@ func TestCorrectFieldOrderingDespiteExecutionOrder(t *testing.T) { }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, - "b": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "b": &types.FieldConfig{ + Type: types.String, }, - "c": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "c": &types.FieldConfig{ + Type: types.String, }, - "d": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "d": &types.FieldConfig{ + Type: types.String, }, - "e": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "e": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -822,18 +822,18 @@ func TestAvoidsRecursion(t *testing.T) { "a": "b", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "a": "b", }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -868,24 +868,24 @@ func TestDoesNotIncludeIllegalFieldsInOutput(t *testing.T) { thisIsIllegalDontIncludeMe }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{}, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Q", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ + Type: types.String, }, }, }), - Mutation: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + Mutation: types.NewObject(types.ObjectConfig{ Name: "M", - Fields: types.GraphQLFieldConfigMap{ - "c": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "c": &types.FieldConfig{ + Type: types.String, }, }, }), @@ -915,33 +915,33 @@ func TestDoesNotIncludeArgumentsThatWereNotSet(t *testing.T) { doc := `{ field(a: true, c: false, e: 0) }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "field": `{"a":true,"c":false,"e":0}`, }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Type", - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "a": &types.GraphQLArgumentConfig{ - Type: types.GraphQLBoolean, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "a": &types.ArgumentConfig{ + Type: types.Boolean, }, - "b": &types.GraphQLArgumentConfig{ - Type: types.GraphQLBoolean, + "b": &types.ArgumentConfig{ + Type: types.Boolean, }, - "c": &types.GraphQLArgumentConfig{ - Type: types.GraphQLBoolean, + "c": &types.ArgumentConfig{ + Type: types.Boolean, }, - "d": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + "d": &types.ArgumentConfig{ + Type: types.Int, }, - "e": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + "e": &types.ArgumentConfig{ + Type: types.Int, }, }, Resolve: func(p types.GQLFRParams) interface{} { @@ -991,7 +991,7 @@ func TestFailsWhenAnIsTypeOfCheckIsNotMet(t *testing.T) { }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "specials": []interface{}{ map[string]interface{}{ @@ -1000,37 +1000,37 @@ func TestFailsWhenAnIsTypeOfCheckIsNotMet(t *testing.T) { nil, }, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Expected value of type "SpecialType" but got: executor_test.testNotSpecialType.`, Locations: []location.SourceLocation{}, }, }, } - specialType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + specialType := types.NewObject(types.ObjectConfig{ Name: "SpecialType", - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { if _, ok := value.(testSpecialType); ok { return true } return false }, - Fields: types.GraphQLFieldConfigMap{ - "value": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "value": &types.FieldConfig{ + Type: types.String, Resolve: func(p types.GQLFRParams) interface{} { return p.Source.(testSpecialType).Value }, }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "specials": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(specialType), + Fields: types.FieldConfigMap{ + "specials": &types.FieldConfig{ + Type: types.NewList(specialType), Resolve: func(p types.GQLFRParams) interface{} { return p.Source.(map[string]interface{})["specials"] }, @@ -1067,22 +1067,22 @@ func TestFailsToExecuteQueryContainingATypeDefinition(t *testing.T) { type Query { foo: String } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ - Message: "GraphQL cannot execute a request containing a ObjectTypeDefinition", + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ + Message: "GraphQL cannot execute a request containing a ObjectDefinition", Locations: []location.SourceLocation{}, }, }, } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "foo": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "foo": &types.FieldConfig{ + Type: types.String, }, }, }), diff --git a/executor/lists_test.go b/executor/lists_test.go index 951d5396..1c0caf65 100644 --- a/executor/lists_test.go +++ b/executor/lists_test.go @@ -10,27 +10,27 @@ import ( "testing" ) -func checkList(t *testing.T, testType types.GraphQLType, testData interface{}, expected *types.GraphQLResult) { +func checkList(t *testing.T, testType types.Type, testData interface{}, expected *types.Result) { data := map[string]interface{}{ "test": testData, } - dataType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + dataType := types.NewObject(types.ObjectConfig{ Name: "DataType", - Fields: types.GraphQLFieldConfigMap{ - "test": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "test": &types.FieldConfig{ Type: testType, }, }, }) - dataType.AddFieldConfig("nest", &types.GraphQLFieldConfig{ + dataType.AddFieldConfig("nest", &types.FieldConfig{ Type: dataType, Resolve: func(p types.GQLFRParams) interface{} { return data }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: dataType, }) if err != nil { @@ -58,11 +58,11 @@ func checkList(t *testing.T, testType types.GraphQLType, testData interface{}, e // Describe [T] Array func TestLists_ListOfNullableObjects_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLList(types.GraphQLInt) + ttype := types.NewList(types.Int) data := []interface{}{ 1, 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -74,11 +74,11 @@ func TestLists_ListOfNullableObjects_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableObjects_ContainsNull(t *testing.T) { - ttype := types.NewGraphQLList(types.GraphQLInt) + ttype := types.NewList(types.Int) data := []interface{}{ 1, nil, 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -90,8 +90,8 @@ func TestLists_ListOfNullableObjects_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableObjects_ReturnsNull(t *testing.T) { - ttype := types.NewGraphQLList(types.GraphQLInt) - expected := &types.GraphQLResult{ + ttype := types.NewList(types.Int) + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, @@ -103,7 +103,7 @@ func TestLists_ListOfNullableObjects_ReturnsNull(t *testing.T) { // Describe [T] Func()Array // equivalent to Promise> func TestLists_ListOfNullableFunc_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLList(types.GraphQLInt) + ttype := types.NewList(types.Int) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -112,7 +112,7 @@ func TestLists_ListOfNullableFunc_ContainsValues(t *testing.T) { 1, 2, } } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -124,7 +124,7 @@ func TestLists_ListOfNullableFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableFunc_ContainsNull(t *testing.T) { - ttype := types.NewGraphQLList(types.GraphQLInt) + ttype := types.NewList(types.Int) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -133,7 +133,7 @@ func TestLists_ListOfNullableFunc_ContainsNull(t *testing.T) { 1, nil, 2, } } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -145,14 +145,14 @@ func TestLists_ListOfNullableFunc_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableFunc_ReturnsNull(t *testing.T) { - ttype := types.NewGraphQLList(types.GraphQLInt) + ttype := types.NewList(types.Int) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` data := func() interface{} { return nil } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, @@ -164,7 +164,7 @@ func TestLists_ListOfNullableFunc_ReturnsNull(t *testing.T) { // Describe [T] Array> // equivalent to Array> func TestLists_ListOfNullableArrayOfFuncContainsValues(t *testing.T) { - ttype := types.NewGraphQLList(types.GraphQLInt) + ttype := types.NewList(types.Int) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -176,7 +176,7 @@ func TestLists_ListOfNullableArrayOfFuncContainsValues(t *testing.T) { return 2 }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -188,7 +188,7 @@ func TestLists_ListOfNullableArrayOfFuncContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableArrayOfFuncContainsNulls(t *testing.T) { - ttype := types.NewGraphQLList(types.GraphQLInt) + ttype := types.NewList(types.Int) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -203,7 +203,7 @@ func TestLists_ListOfNullableArrayOfFuncContainsNulls(t *testing.T) { return 2 }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -217,11 +217,11 @@ func TestLists_ListOfNullableArrayOfFuncContainsNulls(t *testing.T) { // Describe [T]! Array func TestLists_NonNullListOfNullableObjectsContainsValues(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)) + ttype := types.NewNonNull(types.NewList(types.Int)) data := []interface{}{ 1, 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -233,11 +233,11 @@ func TestLists_NonNullListOfNullableObjectsContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableObjectsContainsNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)) + ttype := types.NewNonNull(types.NewList(types.Int)) data := []interface{}{ 1, nil, 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -249,13 +249,13 @@ func TestLists_NonNullListOfNullableObjectsContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableObjectsReturnsNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)) - expected := &types.GraphQLResult{ + ttype := types.NewNonNull(types.NewList(types.Int)) + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", Locations: []location.SourceLocation{ location.SourceLocation{ @@ -271,7 +271,7 @@ func TestLists_NonNullListOfNullableObjectsReturnsNull(t *testing.T) { // Describe [T]! Func()Array // equivalent to Promise> func TestLists_NonNullListOfNullableFunc_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)) + ttype := types.NewNonNull(types.NewList(types.Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -280,7 +280,7 @@ func TestLists_NonNullListOfNullableFunc_ContainsValues(t *testing.T) { 1, 2, } } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -292,7 +292,7 @@ func TestLists_NonNullListOfNullableFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableFunc_ContainsNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)) + ttype := types.NewNonNull(types.NewList(types.Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -301,7 +301,7 @@ func TestLists_NonNullListOfNullableFunc_ContainsNull(t *testing.T) { 1, nil, 2, } } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -313,19 +313,19 @@ func TestLists_NonNullListOfNullableFunc_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableFunc_ReturnsNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)) + ttype := types.NewNonNull(types.NewList(types.Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` data := func() interface{} { return nil } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", Locations: []location.SourceLocation{ location.SourceLocation{ @@ -341,7 +341,7 @@ func TestLists_NonNullListOfNullableFunc_ReturnsNull(t *testing.T) { // Describe [T]! Array> // equivalent to Array> func TestLists_NonNullListOfNullableArrayOfFunc_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)) + ttype := types.NewNonNull(types.NewList(types.Int)) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -353,7 +353,7 @@ func TestLists_NonNullListOfNullableArrayOfFunc_ContainsValues(t *testing.T) { return 2 }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -365,7 +365,7 @@ func TestLists_NonNullListOfNullableArrayOfFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableArrayOfFunc_ContainsNulls(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)) + ttype := types.NewNonNull(types.NewList(types.Int)) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -380,7 +380,7 @@ func TestLists_NonNullListOfNullableArrayOfFunc_ContainsNulls(t *testing.T) { return 2 }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -394,11 +394,11 @@ func TestLists_NonNullListOfNullableArrayOfFunc_ContainsNulls(t *testing.T) { // Describe [T!] Array func TestLists_NullableListOfNonNullObjects_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)) + ttype := types.NewList(types.NewNonNull(types.Int)) data := []interface{}{ 1, 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -410,18 +410,18 @@ func TestLists_NullableListOfNonNullObjects_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullObjects_ContainsNull(t *testing.T) { - ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)) + ttype := types.NewList(types.NewNonNull(types.Int)) data := []interface{}{ 1, nil, 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, }, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", Locations: []location.SourceLocation{ location.SourceLocation{ @@ -435,9 +435,9 @@ func TestLists_NullableListOfNonNullObjects_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullObjects_ReturnsNull(t *testing.T) { - ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)) + ttype := types.NewList(types.NewNonNull(types.Int)) - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, @@ -449,7 +449,7 @@ func TestLists_NullableListOfNonNullObjects_ReturnsNull(t *testing.T) { // Describe [T!] Func()Array // equivalent to Promise> func TestLists_NullableListOfNonNullFunc_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)) + ttype := types.NewList(types.NewNonNull(types.Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -458,7 +458,7 @@ func TestLists_NullableListOfNonNullFunc_ContainsValues(t *testing.T) { 1, 2, } } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -470,7 +470,7 @@ func TestLists_NullableListOfNonNullFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullFunc_ContainsNull(t *testing.T) { - ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)) + ttype := types.NewList(types.NewNonNull(types.Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -479,14 +479,14 @@ func TestLists_NullableListOfNonNullFunc_ContainsNull(t *testing.T) { 1, nil, 2, } } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, }, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", Locations: []location.SourceLocation{ location.SourceLocation{ @@ -500,14 +500,14 @@ func TestLists_NullableListOfNonNullFunc_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullFunc_ReturnsNull(t *testing.T) { - ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)) + ttype := types.NewList(types.NewNonNull(types.Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` data := func() interface{} { return nil } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, @@ -519,7 +519,7 @@ func TestLists_NullableListOfNonNullFunc_ReturnsNull(t *testing.T) { // Describe [T!] Array> // equivalent to Array> func TestLists_NullableListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)) + ttype := types.NewList(types.NewNonNull(types.Int)) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -531,7 +531,7 @@ func TestLists_NullableListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { return 2 }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -543,7 +543,7 @@ func TestLists_NullableListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { - ttype := types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)) + ttype := types.NewList(types.NewNonNull(types.Int)) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -558,7 +558,7 @@ func TestLists_NullableListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { return 2 }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -572,11 +572,11 @@ func TestLists_NullableListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { // Describe [T!]! Array func TestLists_NonNullListOfNonNullObjects_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))) + ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) data := []interface{}{ 1, 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -588,16 +588,16 @@ func TestLists_NonNullListOfNonNullObjects_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullObjects_ContainsNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))) + ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) data := []interface{}{ 1, nil, 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", Locations: []location.SourceLocation{ location.SourceLocation{ @@ -611,14 +611,14 @@ func TestLists_NonNullListOfNonNullObjects_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullObjects_ReturnsNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))) + ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", Locations: []location.SourceLocation{ location.SourceLocation{ @@ -634,7 +634,7 @@ func TestLists_NonNullListOfNonNullObjects_ReturnsNull(t *testing.T) { // Describe [T!]! Func()Array // equivalent to Promise> func TestLists_NonNullListOfNonNullFunc_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))) + ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -643,7 +643,7 @@ func TestLists_NonNullListOfNonNullFunc_ContainsValues(t *testing.T) { 1, 2, } } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -655,7 +655,7 @@ func TestLists_NonNullListOfNonNullFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullFunc_ContainsNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))) + ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -664,12 +664,12 @@ func TestLists_NonNullListOfNonNullFunc_ContainsNull(t *testing.T) { 1, nil, 2, } } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", Locations: []location.SourceLocation{ location.SourceLocation{ @@ -683,19 +683,19 @@ func TestLists_NonNullListOfNonNullFunc_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullFunc_ReturnsNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))) + ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` data := func() interface{} { return nil } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", Locations: []location.SourceLocation{ location.SourceLocation{ @@ -711,7 +711,7 @@ func TestLists_NonNullListOfNonNullFunc_ReturnsNull(t *testing.T) { // Describe [T!]! Array> // equivalent to Array> func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))) + ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -723,7 +723,7 @@ func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { return 2 }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -735,7 +735,7 @@ func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt))) + ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -750,7 +750,7 @@ func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { return 2 }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ diff --git a/executor/mutations_test.go b/executor/mutations_test.go index d4c55d2b..2b3032dd 100644 --- a/executor/mutations_test.go +++ b/executor/mutations_test.go @@ -38,32 +38,32 @@ func (r *testRoot) PromiseAndFailToChangeTheNumber(newNumber int) *testNumberHol } // numberHolderType creates a mapping to testNumberHolder -var numberHolderType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var numberHolderType = types.NewObject(types.ObjectConfig{ Name: "NumberHolder", - Fields: types.GraphQLFieldConfigMap{ - "theNumber": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, + Fields: types.FieldConfigMap{ + "theNumber": &types.FieldConfig{ + Type: types.Int, }, }, }) -var mutationsTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var mutationsTestSchema, _ = types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "numberHolder": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "numberHolder": &types.FieldConfig{ Type: numberHolderType, }, }, }), - Mutation: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + Mutation: types.NewObject(types.ObjectConfig{ Name: "Mutation", - Fields: types.GraphQLFieldConfigMap{ - "immediatelyChangeTheNumber": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "immediatelyChangeTheNumber": &types.FieldConfig{ Type: numberHolderType, - Args: types.GraphQLFieldConfigArgumentMap{ - "newNumber": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + Args: types.FieldConfigArgument{ + "newNumber": &types.ArgumentConfig{ + Type: types.Int, }, }, Resolve: func(p types.GQLFRParams) interface{} { @@ -73,11 +73,11 @@ var mutationsTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ return obj.ImmediatelyChangeTheNumber(newNumber) }, }, - "promiseToChangeTheNumber": &types.GraphQLFieldConfig{ + "promiseToChangeTheNumber": &types.FieldConfig{ Type: numberHolderType, - Args: types.GraphQLFieldConfigArgumentMap{ - "newNumber": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + Args: types.FieldConfigArgument{ + "newNumber": &types.ArgumentConfig{ + Type: types.Int, }, }, Resolve: func(p types.GQLFRParams) interface{} { @@ -87,11 +87,11 @@ var mutationsTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ return obj.PromiseToChangeTheNumber(newNumber) }, }, - "failToChangeTheNumber": &types.GraphQLFieldConfig{ + "failToChangeTheNumber": &types.FieldConfig{ Type: numberHolderType, - Args: types.GraphQLFieldConfigArgumentMap{ - "newNumber": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + Args: types.FieldConfigArgument{ + "newNumber": &types.ArgumentConfig{ + Type: types.Int, }, }, Resolve: func(p types.GQLFRParams) interface{} { @@ -101,11 +101,11 @@ var mutationsTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ return obj.FailToChangeTheNumber(newNumber) }, }, - "promiseAndFailToChangeTheNumber": &types.GraphQLFieldConfig{ + "promiseAndFailToChangeTheNumber": &types.FieldConfig{ Type: numberHolderType, - Args: types.GraphQLFieldConfigArgumentMap{ - "newNumber": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + Args: types.FieldConfigArgument{ + "newNumber": &types.ArgumentConfig{ + Type: types.Int, }, }, Resolve: func(p types.GQLFRParams) interface{} { @@ -140,7 +140,7 @@ func TestMutations_ExecutionOrdering_EvaluatesMutationsSerially(t *testing.T) { } }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "first": map[string]interface{}{ "theNumber": 1, @@ -200,7 +200,7 @@ func TestMutations_EvaluatesMutationsCorrectlyInThePresenceOfAFailedMutation(t * } }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "first": map[string]interface{}{ "theNumber": 1, @@ -217,14 +217,14 @@ func TestMutations_EvaluatesMutationsCorrectlyInThePresenceOfAFailedMutation(t * }, "sixth": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot change the number`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 8, Column: 7}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot change the number`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 17, Column: 7}, diff --git a/executor/nonnull_test.go b/executor/nonnull_test.go index 63db8385..3a035803 100644 --- a/executor/nonnull_test.go +++ b/executor/nonnull_test.go @@ -47,25 +47,25 @@ var nullingData = map[string]interface{}{ }, } -var dataType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var dataType = types.NewObject(types.ObjectConfig{ Name: "DataType", - Fields: types.GraphQLFieldConfigMap{ - "sync": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "sync": &types.FieldConfig{ + Type: types.String, }, - "nonNullSync": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(types.GraphQLString), + "nonNullSync": &types.FieldConfig{ + Type: types.NewNonNull(types.String), }, - "promise": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "promise": &types.FieldConfig{ + Type: types.String, }, - "nonNullPromise": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(types.GraphQLString), + "nonNullPromise": &types.FieldConfig{ + Type: types.NewNonNull(types.String), }, }, }) -var nonNullTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ +var nonNullTestSchema, _ = types.NewSchema(types.SchemaConfig{ Query: dataType, }) @@ -96,17 +96,17 @@ func init() { return nullingData } - dataType.AddFieldConfig("nest", &types.GraphQLFieldConfig{ + dataType.AddFieldConfig("nest", &types.FieldConfig{ Type: dataType, }) - dataType.AddFieldConfig("nonNullNest", &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(dataType), + dataType.AddFieldConfig("nonNullNest", &types.FieldConfig{ + Type: types.NewNonNull(dataType), }) - dataType.AddFieldConfig("promiseNest", &types.GraphQLFieldConfig{ + dataType.AddFieldConfig("promiseNest", &types.FieldConfig{ Type: dataType, }) - dataType.AddFieldConfig("nonNullPromiseNest", &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(dataType), + dataType.AddFieldConfig("nonNullPromiseNest", &types.FieldConfig{ + Type: types.NewNonNull(dataType), }) } @@ -117,12 +117,12 @@ func TestNonNull_NullsANullableFieldThatThrowsSynchronously(t *testing.T) { sync } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "sync": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: syncError, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -155,12 +155,12 @@ func TestNonNull_NullsANullableFieldThatThrowsInAPromise(t *testing.T) { promise } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "promise": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: promiseError, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -195,12 +195,12 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANullableFieldThat } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: nonNullSyncError, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -235,12 +235,12 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: nonNullPromiseError, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -275,12 +275,12 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: nonNullSyncError, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -315,12 +315,12 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: nonNullPromiseError, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -377,7 +377,7 @@ func TestNonNull_NullsAComplexTreeOfNullableFieldsThatThrow(t *testing.T) { } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "sync": nil, @@ -404,74 +404,74 @@ func TestNonNull_NullsAComplexTreeOfNullableFieldsThatThrow(t *testing.T) { }, }, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: syncError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 4, Column: 11}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: syncError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 7, Column: 13}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: syncError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 11, Column: 13}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: syncError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 16, Column: 11}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: syncError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 19, Column: 13}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: syncError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 23, Column: 13}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: promiseError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 5, Column: 11}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: promiseError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 8, Column: 13}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: promiseError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 12, Column: 13}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: promiseError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 17, Column: 11}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: promiseError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 20, Column: 13}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: promiseError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 24, Column: 13}, @@ -550,33 +550,33 @@ func TestNonNull_NullsTheFirstNullableObjectAfterAFieldThrowsInALongChainOfField } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, "promiseNest": nil, "anotherNest": nil, "anotherPromiseNest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: nonNullSyncError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 8, Column: 19}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: nonNullSyncError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 19, Column: 19}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: nonNullPromiseError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 30, Column: 19}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: nonNullPromiseError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 41, Column: 19}, @@ -613,7 +613,7 @@ func TestNonNull_NullsANullableFieldThatSynchronouslyReturnsNull(t *testing.T) { sync } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "sync": nil, }, @@ -644,7 +644,7 @@ func TestNonNull_NullsANullableFieldThatSynchronouslyReturnsNullInAPromise(t *te promise } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "promise": nil, }, @@ -677,12 +677,12 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 4, Column: 11}, @@ -715,12 +715,12 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 4, Column: 11}, @@ -754,12 +754,12 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 4, Column: 11}, @@ -792,12 +792,12 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 4, Column: 11}, @@ -851,7 +851,7 @@ func TestNonNull_NullsAComplexTreeOfNullableFieldsThatReturnNull(t *testing.T) { } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "sync": nil, @@ -948,33 +948,33 @@ func TestNonNull_NullsTheFirstNullableObjectAfterAFieldReturnsNullInALongChainOf } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nest": nil, "promiseNest": nil, "anotherNest": nil, "anotherPromiseNest": nil, }, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 8, Column: 19}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 19, Column: 19}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 30, Column: 19}, }, }, - graphqlerrors.GraphQLFormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 41, Column: 19}, @@ -1009,10 +1009,10 @@ func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldThrows(t *testing.T) { doc := ` query Q { nonNullSync } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: nonNullSyncError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 2, Column: 17}, @@ -1041,10 +1041,10 @@ func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldErrors(t *testing.T) { doc := ` query Q { nonNullPromise } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: nonNullPromiseError, Locations: []location.SourceLocation{ location.SourceLocation{Line: 2, Column: 17}, @@ -1073,10 +1073,10 @@ func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldReturnsNull(t *testing.T) doc := ` query Q { nonNullSync } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 2, Column: 17}, @@ -1105,10 +1105,10 @@ func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldResolvesNull(t *testing.T doc := ` query Q { nonNullPromise } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, Locations: []location.SourceLocation{ location.SourceLocation{Line: 2, Column: 17}, diff --git a/executor/union_interface_test.go b/executor/union_interface_test.go index d2c3559b..f397f734 100644 --- a/executor/union_interface_test.go +++ b/executor/union_interface_test.go @@ -28,56 +28,56 @@ type testPerson struct { Friends []testNamedType `json:"friends"` } -var namedType = types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ +var namedType = types.NewInterface(types.InterfaceConfig{ Name: "Named", - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, }, }, }) -var dogType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var dogType = types.NewObject(types.ObjectConfig{ Name: "Dog", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ namedType, }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, }, - "barks": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "barks": &types.FieldConfig{ + Type: types.Boolean, }, }, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testDog2) return ok }, }) -var catType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var catType = types.NewObject(types.ObjectConfig{ Name: "Cat", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ namedType, }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, }, - "meows": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "meows": &types.FieldConfig{ + Type: types.Boolean, }, }, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testCat2) return ok }, }) -var petType = types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ +var petType = types.NewUnion(types.UnionConfig{ Name: "Pet", - Types: []*types.GraphQLObjectType{ + Types: []*types.Object{ dogType, catType, }, - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { if _, ok := value.(*testCat2); ok { return catType } @@ -87,29 +87,29 @@ var petType = types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ return nil }, }) -var personType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var personType = types.NewObject(types.ObjectConfig{ Name: "Person", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ namedType, }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, }, - "pets": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(petType), + "pets": &types.FieldConfig{ + Type: types.NewList(petType), }, - "friends": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(namedType), + "friends": &types.FieldConfig{ + Type: types.NewList(namedType), }, }, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { _, ok := value.(*testPerson) return ok }, }) -var unionInterfaceTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ +var unionInterfaceTestSchema, _ = types.NewSchema(types.SchemaConfig{ Query: personType, }) @@ -151,7 +151,7 @@ func TestUnionIntersectionTypes_CanIntrospectOnUnionAndIntersectionTypes(t *test } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "Named": map[string]interface{}{ "kind": "INTERFACE", @@ -224,7 +224,7 @@ func TestUnionIntersectionTypes_ExecutesUsingUnionTypes(t *testing.T) { } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -278,7 +278,7 @@ func TestUnionIntersectionTypes_ExecutesUnionTypesWithInlineFragments(t *testing } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -328,7 +328,7 @@ func TestUnionIntersectionTypes_ExecutesUsingInterfaceTypes(t *testing.T) { } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -381,7 +381,7 @@ func TestUnionIntersectionTypes_ExecutesInterfaceTypesWithInlineFragments(t *tes } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -449,7 +449,7 @@ func TestUnionIntersectionTypes_AllowsFragmentConditionsToBeAbstractTypes(t *tes } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -497,41 +497,41 @@ func TestUnionIntersectionTypes_AllowsFragmentConditionsToBeAbstractTypes(t *tes } func TestUnionIntersectionTypes_GetsExecutionInfoInResolver(t *testing.T) { - var encounteredSchema *types.GraphQLSchema + var encounteredSchema *types.Schema var encounteredRootValue interface{} - var personType2 *types.GraphQLObjectType + var personType2 *types.Object - namedType2 := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + namedType2 := types.NewInterface(types.InterfaceConfig{ Name: "Named", - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, }, }, - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { encounteredSchema = &info.Schema encounteredRootValue = info.RootValue return personType2 }, }) - personType2 = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + personType2 = types.NewObject(types.ObjectConfig{ Name: "Person", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ namedType2, }, - Fields: types.GraphQLFieldConfigMap{ - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "name": &types.FieldConfig{ + Type: types.String, }, - "friends": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(namedType2), + "friends": &types.FieldConfig{ + Type: types.NewList(namedType2), }, }, }) - schema2, _ := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema2, _ := types.NewSchema(types.SchemaConfig{ Query: personType2, }) @@ -543,7 +543,7 @@ func TestUnionIntersectionTypes_GetsExecutionInfoInResolver(t *testing.T) { } doc := `{ name, friends { name } }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "name": "John", "friends": []interface{}{ diff --git a/executor/values.go b/executor/values.go index 6800f54f..21bed3df 100644 --- a/executor/values.go +++ b/executor/values.go @@ -14,8 +14,8 @@ import ( // Prepares an object map of variableValues of the correct type based on the // provided variable definitions and arbitrary input. If the input cannot be -// parsed to match the variable definitions, a GraphQLError will be returned. -func getVariableValues(schema types.GraphQLSchema, definitionASTs []*ast.VariableDefinition, inputs map[string]interface{}) (map[string]interface{}, error) { +// parsed to match the variable definitions, a Error will be returned. +func getVariableValues(schema types.Schema, definitionASTs []*ast.VariableDefinition, inputs map[string]interface{}) (map[string]interface{}, error) { values := map[string]interface{}{} for _, defAST := range definitionASTs { if defAST == nil || defAST.Variable == nil || defAST.Variable.Name == nil { @@ -33,7 +33,7 @@ func getVariableValues(schema types.GraphQLSchema, definitionASTs []*ast.Variabl // Prepares an object map of argument values given a list of argument // definitions and list of argument AST nodes. -func getArgumentValues(argDefs []*types.GraphQLArgument, argASTs []*ast.Argument, variableVariables map[string]interface{}) (map[string]interface{}, error) { +func getArgumentValues(argDefs []*types.Argument, argASTs []*ast.Argument, variableVariables map[string]interface{}) (map[string]interface{}, error) { argASTMap := map[string]*ast.Argument{} for _, argAST := range argASTs { @@ -62,7 +62,7 @@ func getArgumentValues(argDefs []*types.GraphQLArgument, argASTs []*ast.Argument // Given a variable definition, and any value of input, return a value which // adheres to the variable definition, or throw an error. -func getVariableValue(schema types.GraphQLSchema, definitionAST *ast.VariableDefinition, input interface{}) (interface{}, error) { +func getVariableValue(schema types.Schema, definitionAST *ast.VariableDefinition, input interface{}) (interface{}, error) { ttype, err := typeFromAST(schema, definitionAST.Type) if err != nil { return nil, err @@ -70,7 +70,7 @@ func getVariableValue(schema types.GraphQLSchema, definitionAST *ast.VariableDef variable := definitionAST.Variable if ttype == nil || !types.IsInputType(ttype) { - return "", graphqlerrors.NewGraphQLError( + return "", graphqlerrors.NewError( fmt.Sprintf(`Variable "$%v" expected value of type `+ `"%v" which cannot be used as an input type.`, variable.Name.Value, printer.Print(definitionAST.Type)), []ast.Node{definitionAST}, @@ -92,7 +92,7 @@ func getVariableValue(schema types.GraphQLSchema, definitionAST *ast.VariableDef return coerceValue(ttype, input), nil } if isNullish(input) { - return "", graphqlerrors.NewGraphQLError( + return "", graphqlerrors.NewError( fmt.Sprintf(`Variable "$%v" of required type `+ `"%v" was not provided.`, variable.Name.Value, printer.Print(definitionAST.Type)), []ast.Node{definitionAST}, @@ -106,7 +106,7 @@ func getVariableValue(schema types.GraphQLSchema, definitionAST *ast.VariableDef if err == nil { inputStr = string(b) } - return "", graphqlerrors.NewGraphQLError( + return "", graphqlerrors.NewError( fmt.Sprintf(`Variable "$%v" expected value of type `+ `"%v" but got: %v.`, variable.Name.Value, printer.Print(definitionAST.Type), inputStr), []ast.Node{definitionAST}, @@ -117,14 +117,14 @@ func getVariableValue(schema types.GraphQLSchema, definitionAST *ast.VariableDef } // Given a type and any value, return a runtime value coerced to match the type. -func coerceValue(ttype types.GraphQLInputType, value interface{}) interface{} { - if ttype, ok := ttype.(*types.GraphQLNonNull); ok { +func coerceValue(ttype types.Input, value interface{}) interface{} { + if ttype, ok := ttype.(*types.NonNull); ok { return coerceValue(ttype.OfType, value) } if isNullish(value) { return nil } - if ttype, ok := ttype.(*types.GraphQLList); ok { + if ttype, ok := ttype.(*types.List); ok { itemType := ttype.OfType valType := reflect.ValueOf(value) if valType.Kind() == reflect.Slice { @@ -139,7 +139,7 @@ func coerceValue(ttype types.GraphQLInputType, value interface{}) interface{} { val := coerceValue(itemType, value) return []interface{}{val} } - if ttype, ok := ttype.(*types.GraphQLInputObjectType); ok { + if ttype, ok := ttype.(*types.InputObject); ok { valueMap, ok := value.(map[string]interface{}) if !ok { @@ -161,12 +161,12 @@ func coerceValue(ttype types.GraphQLInputType, value interface{}) interface{} { } switch ttype := ttype.(type) { - case *types.GraphQLScalarType: + case *types.Scalar: parsed := ttype.ParseValue(value) if !isNullish(parsed) { return parsed } - case *types.GraphQLEnumType: + case *types.Enum: parsed := ttype.ParseValue(value) if !isNullish(parsed) { return parsed @@ -178,20 +178,20 @@ func coerceValue(ttype types.GraphQLInputType, value interface{}) interface{} { // graphql-js/src/utilities.js` // TODO: figure out where to organize utils -func typeFromAST(schema types.GraphQLSchema, inputTypeAST ast.Type) (types.GraphQLType, error) { +func typeFromAST(schema types.Schema, inputTypeAST ast.Type) (types.Type, error) { switch inputTypeAST := inputTypeAST.(type) { case *ast.ListType: innerType, err := typeFromAST(schema, inputTypeAST.Type) if err != nil { return nil, err } - return types.NewGraphQLList(innerType), nil + return types.NewList(innerType), nil case *ast.NonNullType: innerType, err := typeFromAST(schema, inputTypeAST.Type) if err != nil { return nil, err } - return types.NewGraphQLNonNull(innerType), nil + return types.NewNonNull(innerType), nil case *ast.NamedType: nameValue := "" if inputTypeAST.Name != nil { @@ -208,8 +208,8 @@ func typeFromAST(schema types.GraphQLSchema, inputTypeAST ast.Type) (types.Graph // Given a value and a GraphQL type, determine if the value will be // accepted for that type. This is primarily useful for validating the // runtime values of query variables. -func isValidInputValue(value interface{}, ttype types.GraphQLInputType) bool { - if ttype, ok := ttype.(*types.GraphQLNonNull); ok { +func isValidInputValue(value interface{}, ttype types.Input) bool { + if ttype, ok := ttype.(*types.NonNull); ok { if isNullish(value) { return false } @@ -221,7 +221,7 @@ func isValidInputValue(value interface{}, ttype types.GraphQLInputType) bool { } switch ttype := ttype.(type) { - case *types.GraphQLList: + case *types.List: itemType := ttype.OfType valType := reflect.ValueOf(value) if valType.Kind() == reflect.Ptr { @@ -238,7 +238,7 @@ func isValidInputValue(value interface{}, ttype types.GraphQLInputType) bool { } return isValidInputValue(value, itemType) - case *types.GraphQLInputObjectType: + case *types.InputObject: valueMap, ok := value.(map[string]interface{}) if !ok { return false @@ -262,10 +262,10 @@ func isValidInputValue(value interface{}, ttype types.GraphQLInputType) bool { } switch ttype := ttype.(type) { - case *types.GraphQLScalarType: + case *types.Scalar: parsedVal := ttype.ParseValue(value) return !isNullish(parsedVal) - case *types.GraphQLEnumType: + case *types.Enum: parsedVal := ttype.ParseValue(value) return !isNullish(parsedVal) } @@ -304,9 +304,9 @@ func isNullish(value interface{}) bool { * | Int / Float | Number | * */ -func valueFromAST(valueAST ast.Value, ttype types.GraphQLInputType, variables map[string]interface{}) interface{} { +func valueFromAST(valueAST ast.Value, ttype types.Input, variables map[string]interface{}) interface{} { - if ttype, ok := ttype.(*types.GraphQLNonNull); ok { + if ttype, ok := ttype.(*types.NonNull); ok { val := valueFromAST(valueAST, ttype.OfType, variables) return val } @@ -333,7 +333,7 @@ func valueFromAST(valueAST ast.Value, ttype types.GraphQLInputType, variables ma return variableVal } - if ttype, ok := ttype.(*types.GraphQLList); ok { + if ttype, ok := ttype.(*types.List); ok { itemType := ttype.OfType if valueAST, ok := valueAST.(*ast.ListValue); ok && valueAST.Kind == kinds.ListValue { values := []interface{}{} @@ -347,7 +347,7 @@ func valueFromAST(valueAST ast.Value, ttype types.GraphQLInputType, variables ma return []interface{}{v} } - if ttype, ok := ttype.(*types.GraphQLInputObjectType); ok { + if ttype, ok := ttype.(*types.InputObject); ok { valueAST, ok := valueAST.(*ast.ObjectValue) if !ok { return nil @@ -379,12 +379,12 @@ func valueFromAST(valueAST ast.Value, ttype types.GraphQLInputType, variables ma } switch ttype := ttype.(type) { - case *types.GraphQLScalarType: + case *types.Scalar: parsed := ttype.ParseLiteral(valueAST) if !isNullish(parsed) { return parsed } - case *types.GraphQLEnumType: + case *types.Enum: parsed := ttype.ParseLiteral(valueAST) if !isNullish(parsed) { return parsed @@ -395,7 +395,7 @@ func valueFromAST(valueAST ast.Value, ttype types.GraphQLInputType, variables ma func invariant(condition bool, message string) error { if !condition { - return graphqlerrors.NewGraphQLFormattedError(message) + return graphqlerrors.NewFormattedError(message) } return nil } diff --git a/executor/variables_test.go b/executor/variables_test.go index 5cbdc957..830ab6c7 100644 --- a/executor/variables_test.go +++ b/executor/variables_test.go @@ -12,7 +12,7 @@ import ( "testing" ) -var testComplexScalar *types.GraphQLScalarType = types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ +var testComplexScalar *types.Scalar = types.NewScalar(types.ScalarConfig{ Name: "ComplexScalar", Serialize: func(value interface{}) interface{} { if value == "DeserializedValue" { @@ -35,17 +35,17 @@ var testComplexScalar *types.GraphQLScalarType = types.NewGraphQLScalarType(type }, }) -var testInputObject *types.GraphQLInputObjectType = types.NewGraphQLInputObjectType(types.InputObjectConfig{ +var testInputObject *types.InputObject = types.NewInputObject(types.InputObjectConfig{ Name: "TestInputObject", Fields: types.InputObjectConfigFieldMap{ "a": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, }, "b": &types.InputObjectFieldConfig{ - Type: types.NewGraphQLList(types.GraphQLString), + Type: types.NewList(types.String), }, "c": &types.InputObjectFieldConfig{ - Type: types.NewGraphQLNonNull(types.GraphQLString), + Type: types.NewNonNull(types.String), }, "d": &types.InputObjectFieldConfig{ Type: testComplexScalar, @@ -65,78 +65,78 @@ func inputResolved(p types.GQLFRParams) interface{} { return string(b) } -var testType *types.GraphQLObjectType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var testType *types.Object = types.NewObject(types.ObjectConfig{ Name: "TestType", - Fields: types.GraphQLFieldConfigMap{ - "fieldWithObjectInput": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ + Fields: types.FieldConfigMap{ + "fieldWithObjectInput": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ Type: testInputObject, }, }, Resolve: inputResolved, }, - "fieldWithNullableStringInput": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + "fieldWithNullableStringInput": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, Resolve: inputResolved, }, - "fieldWithNonNullableStringInput": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.NewGraphQLNonNull(types.GraphQLString), + "fieldWithNonNullableStringInput": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.NewNonNull(types.String), }, }, Resolve: inputResolved, }, - "fieldWithDefaultArgumentValue": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + "fieldWithDefaultArgumentValue": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, DefaultValue: "Hello World", }, }, Resolve: inputResolved, }, - "list": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.NewGraphQLList(types.GraphQLString), + "list": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.NewList(types.String), }, }, Resolve: inputResolved, }, - "nnList": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLString)), + "nnList": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.NewNonNull(types.NewList(types.String)), }, }, Resolve: inputResolved, }, - "listNN": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLString)), + "listNN": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.NewList(types.NewNonNull(types.String)), }, }, Resolve: inputResolved, }, - "nnListNN": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.NewGraphQLNonNull(types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLString))), + "nnListNN": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.NewNonNull(types.NewList(types.NewNonNull(types.String))), }, }, Resolve: inputResolved, @@ -144,7 +144,7 @@ var testType *types.GraphQLObjectType = types.NewGraphQLObjectType(types.GraphQL }, }) -var variablesTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ +var variablesTestSchema, _ = types.NewSchema(types.SchemaConfig{ Query: testType, }) @@ -154,7 +154,7 @@ func TestVariables_ObjectsAndNullability_UsingInlineStructs_ExecutesWithComplexI fieldWithObjectInput(input: {a: "foo", b: ["bar"], c: "baz"}) } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, @@ -181,7 +181,7 @@ func TestVariables_ObjectsAndNullability_UsingInlineStructs_ProperlyParsesSingle fieldWithObjectInput(input: {a: "foo", b: "bar", c: "baz"}) } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, @@ -208,7 +208,7 @@ func TestVariables_ObjectsAndNullability_UsingInlineStructs_DoesNotUseIncorrectV fieldWithObjectInput(input: ["foo", "bar", "baz"]) } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithObjectInput": nil, }, @@ -247,7 +247,7 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ExecutesWithComplexInput "c": "baz", }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, @@ -277,7 +277,7 @@ func TestVariables_ObjectsAndNullability_UsingVariables_UsesDefaultValueWhenNotP fieldWithObjectInput(input: $input) } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, @@ -306,7 +306,7 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ProperlyParsesSingleValu "c": "baz", }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, @@ -335,7 +335,7 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ExecutesWithComplexScala "d": "SerializedValue", }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"c":"foo","d":"DeserializedValue"}`, }, @@ -365,10 +365,10 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnNullForNestedNon "c": nil, }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: {"a":"foo","b":"bar","c":null}.`, Locations: []location.SourceLocation{ @@ -400,10 +400,10 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnIncorrectType(t params := map[string]interface{}{ "input": "foo bar", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: "foo bar".`, Locations: []location.SourceLocation{ @@ -438,10 +438,10 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnOmissionOfNested "b": "bar", }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: {"a":"foo","b":"bar"}.`, Locations: []location.SourceLocation{ @@ -478,10 +478,10 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnAdditionOfUnknow "d": "dog", }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: {"a":"foo","b":"bar","c":"baz","d":"dog"}.`, Locations: []location.SourceLocation{ @@ -516,7 +516,7 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeOmitted(t *testing.T) fieldWithNullableStringInput } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": nil, }, @@ -543,7 +543,7 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeOmittedInAVariable(t fieldWithNullableStringInput(input: $value) } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": nil, }, @@ -570,7 +570,7 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeOmittedInAnUnlistedVa fieldWithNullableStringInput(input: $value) } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": nil, }, @@ -600,7 +600,7 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeSetToNullInAVariable( params := map[string]interface{}{ "value": nil, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": nil, }, @@ -631,7 +631,7 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeSetToAValueInAVariabl params := map[string]interface{}{ "value": "a", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": `"a"`, }, @@ -659,7 +659,7 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeSetToAValueDirectly(t fieldWithNullableStringInput(input: "a") } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": `"a"`, }, @@ -689,10 +689,10 @@ func TestVariables_NonNullableScalars_DoesNotAllowNonNullableInputsToBeOmittedIn } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$value" of required type "String!" was not provided.`, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -728,10 +728,10 @@ func TestVariables_NonNullableScalars_DoesNotAllowNonNullableInputsToBeSetToNull params := map[string]interface{}{ "value": nil, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$value" of required type "String!" was not provided.`, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -768,7 +768,7 @@ func TestVariables_NonNullableScalars_AllowsNonNullableInputsToBeSetToAValueInAV params := map[string]interface{}{ "value": "a", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithNonNullableStringInput": `"a"`, }, @@ -801,7 +801,7 @@ func TestVariables_NonNullableScalars_AllowsNonNullableInputsToBeSetToAValueDire "value": "a", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithNonNullableStringInput": `"a"`, }, @@ -834,7 +834,7 @@ func TestVariables_NonNullableScalars_PassesAlongNullForNonNullableInputsIfExpli "value": "a", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithNonNullableStringInput": nil, }, @@ -867,7 +867,7 @@ func TestVariables_ListsAndNullability_AllowsListsToBeNull(t *testing.T) { "input": nil, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "list": nil, }, @@ -898,7 +898,7 @@ func TestVariables_ListsAndNullability_AllowsListsToContainValues(t *testing.T) "input": []interface{}{"A"}, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "list": `["A"]`, }, @@ -929,7 +929,7 @@ func TestVariables_ListsAndNullability_AllowsListsToContainNull(t *testing.T) { "input": []interface{}{"A", nil, "B"}, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "list": `["A",null,"B"]`, }, @@ -956,10 +956,10 @@ func TestVariables_ListsAndNullability_DoesNotAllowNonNullListsToBeNull(t *testi nnList(input: $input) } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" of required type "[String]!" was not provided.`, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -993,7 +993,7 @@ func TestVariables_ListsAndNullability_AllowsNonNullListsToContainValues(t *test params := map[string]interface{}{ "input": []interface{}{"A"}, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nnList": `["A"]`, }, @@ -1023,7 +1023,7 @@ func TestVariables_ListsAndNullability_AllowsNonNullListsToContainNull(t *testin params := map[string]interface{}{ "input": []interface{}{"A", nil, "B"}, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nnList": `["A",null,"B"]`, }, @@ -1053,7 +1053,7 @@ func TestVariables_ListsAndNullability_AllowsListsOfNonNullsToBeNull(t *testing. params := map[string]interface{}{ "input": nil, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "listNN": nil, }, @@ -1083,7 +1083,7 @@ func TestVariables_ListsAndNullability_AllowsListsOfNonNullsToContainValues(t *t params := map[string]interface{}{ "input": []interface{}{"A"}, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "listNN": `["A"]`, }, @@ -1113,10 +1113,10 @@ func TestVariables_ListsAndNullability_DoesNotAllowListOfNonNullsToContainNull(t params := map[string]interface{}{ "input": []interface{}{"A", nil, "B"}, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "[String!]" but got: ` + `["A",null,"B"].`, Locations: []location.SourceLocation{ @@ -1152,10 +1152,10 @@ func TestVariables_ListsAndNullability_DoesNotAllowNonNullListOfNonNullsToBeNull params := map[string]interface{}{ "input": nil, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" of required type "[String!]!" was not provided.`, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -1190,7 +1190,7 @@ func TestVariables_ListsAndNullability_AllowsNonNullListsOfNonNulsToContainValue params := map[string]interface{}{ "input": []interface{}{"A"}, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "nnListNN": `["A"]`, }, @@ -1220,10 +1220,10 @@ func TestVariables_ListsAndNullability_DoesNotAllowNonNullListOfNonNullsToContai params := map[string]interface{}{ "input": []interface{}{"A", nil, "B"}, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "[String!]!" but got: ` + `["A",null,"B"].`, Locations: []location.SourceLocation{ @@ -1261,10 +1261,10 @@ func TestVariables_ListsAndNullability_DoesNotAllowInvalidTypesToBeUsedAsValues( "list": []interface{}{"A", "B"}, }, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestType!" which cannot be used as an input type.`, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -1299,10 +1299,10 @@ func TestVariables_ListsAndNullability_DoesNotAllowUnknownTypesToBeUsedAsValues( params := map[string]interface{}{ "input": "whoknows", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "UnknownType!" which cannot be used as an input type.`, Locations: []location.SourceLocation{ location.SourceLocation{ @@ -1335,7 +1335,7 @@ func TestVariables_UsesArgumentDefaultValues_WhenNoArgumentProvided(t *testing.T fieldWithDefaultArgumentValue } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithDefaultArgumentValue": `"Hello World"`, }, @@ -1361,7 +1361,7 @@ func TestVariables_UsesArgumentDefaultValues_WhenNullableVariableProvided(t *tes fieldWithDefaultArgumentValue(input: $optional) } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithDefaultArgumentValue": `"Hello World"`, }, @@ -1387,7 +1387,7 @@ func TestVariables_UsesArgumentDefaultValues_WhenArgumentProvidedCannotBeParsed( fieldWithDefaultArgumentValue(input: WRONG_TYPE) } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "fieldWithDefaultArgumentValue": `"Hello World"`, }, diff --git a/graphql.go b/graphql.go index 6c5ce2ee..694f9eba 100644 --- a/graphql.go +++ b/graphql.go @@ -9,22 +9,22 @@ import ( "github.com/chris-ramon/graphql/validator" ) -type GraphqlParams struct { - Schema types.GraphQLSchema +type Params struct { + Schema types.Schema RequestString string RootObject map[string]interface{} VariableValues map[string]interface{} OperationName string } -func Graphql(p GraphqlParams, resultChannel chan *types.GraphQLResult) { +func Graphql(p Params, resultChannel chan *types.Result) { source := source.NewSource(&source.Source{ Body: p.RequestString, Name: "GraphQL request", }) AST, err := parser.Parse(parser.ParseParams{Source: source}) if err != nil { - result := types.GraphQLResult{ + result := types.Result{ Errors: graphqlerrors.FormatErrors(err), } resultChannel <- &result @@ -33,7 +33,7 @@ func Graphql(p GraphqlParams, resultChannel chan *types.GraphQLResult) { validationResult := validator.ValidateDocument(p.Schema, AST) if !validationResult.IsValid { - result := types.GraphQLResult{ + result := types.Result{ Errors: validationResult.Errors, } resultChannel <- &result diff --git a/graphql_test.go b/graphql_test.go index 2ae18f1d..aa1b42f0 100644 --- a/graphql_test.go +++ b/graphql_test.go @@ -11,7 +11,7 @@ import ( type T struct { Query string - Schema types.GraphQLSchema + Schema types.Schema Expected interface{} } @@ -26,7 +26,7 @@ var ( } `, Schema: testutil.StarWarsSchema, - Expected: &types.GraphQLResult{ + Expected: &types.Result{ Data: map[string]interface{}{ "hero": map[string]interface{}{ "name": "R2-D2", @@ -47,7 +47,7 @@ var ( } `, Schema: testutil.StarWarsSchema, - Expected: &types.GraphQLResult{ + Expected: &types.Result{ Data: map[string]interface{}{ "hero": map[string]interface{}{ "id": "2001", @@ -72,7 +72,7 @@ var ( func TestQuery(t *testing.T) { for _, test := range Tests { - graphqlParams := GraphqlParams{ + graphqlParams := Params{ Schema: test.Schema, RequestString: test.Query, } @@ -80,8 +80,8 @@ func TestQuery(t *testing.T) { } } -func testGraphql(test T, p GraphqlParams, t *testing.T) { - resultChannel := make(chan *types.GraphQLResult) +func testGraphql(test T, p Params, t *testing.T) { + resultChannel := make(chan *types.Result) go Graphql(p, resultChannel) result := <-resultChannel if len(result.Errors) > 0 { @@ -99,13 +99,13 @@ func TestBasicGraphQLExample(t *testing.T) { return "world" } - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "RootQueryType", - Fields: types.GraphQLFieldConfigMap{ - "hello": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "hello": &types.FieldConfig{ Description: "Returns `world`", - Type: types.GraphQLString, + Type: types.String, Resolve: helloFieldResolved, }, }, @@ -120,8 +120,8 @@ func TestBasicGraphQLExample(t *testing.T) { "hello": "world", } - resultChannel := make(chan *types.GraphQLResult) - go Graphql(GraphqlParams{ + resultChannel := make(chan *types.Result) + go Graphql(Params{ Schema: schema, RequestString: query, }, resultChannel) diff --git a/language/ast/definitions.go b/language/ast/definitions.go index a1bfa5de..663945d6 100644 --- a/language/ast/definitions.go +++ b/language/ast/definitions.go @@ -14,7 +14,7 @@ type Definition interface { // Ensure that all definition types implements Definition interface var _ Definition = (*OperationDefinition)(nil) var _ Definition = (*FragmentDefinition)(nil) -var _ Definition = (TypeDefinition)(nil) +var _ Definition = (Definition)(nil) // OperationDefinition implements Node, Definition type OperationDefinition struct { diff --git a/language/ast/node.go b/language/ast/node.go index af2e1274..f1ba7c70 100644 --- a/language/ast/node.go +++ b/language/ast/node.go @@ -29,15 +29,15 @@ var _ Node = (*ObjectField)(nil) var _ Node = (*Directive)(nil) var _ Node = (*ListType)(nil) var _ Node = (*NonNullType)(nil) -var _ Node = (*ObjectTypeDefinition)(nil) +var _ Node = (*ObjectDefinition)(nil) var _ Node = (*FieldDefinition)(nil) var _ Node = (*InputValueDefinition)(nil) -var _ Node = (*InterfaceTypeDefinition)(nil) -var _ Node = (*UnionTypeDefinition)(nil) -var _ Node = (*ScalarTypeDefinition)(nil) -var _ Node = (*EnumTypeDefinition)(nil) +var _ Node = (*InterfaceDefinition)(nil) +var _ Node = (*UnionDefinition)(nil) +var _ Node = (*ScalarDefinition)(nil) +var _ Node = (*EnumDefinition)(nil) var _ Node = (*EnumValueDefinition)(nil) -var _ Node = (*InputObjectTypeDefinition)(nil) +var _ Node = (*InputObjectDefinition)(nil) var _ Node = (*TypeExtensionDefinition)(nil) // TODO: File issue in `graphql-js` where NamedType is not diff --git a/language/ast/type_definitions.go b/language/ast/type_definitions.go index e7d8a72a..2c7ad902 100644 --- a/language/ast/type_definitions.go +++ b/language/ast/type_definitions.go @@ -4,25 +4,17 @@ import ( "github.com/chris-ramon/graphql/language/kinds" ) -// TypeDefinition implements Definition -type TypeDefinition interface { - // TODO: determine the minimal set of interface for `TypeDefinition` - GetOperation() string - GetVariableDefinitions() []*VariableDefinition - GetSelectionSet() *SelectionSet -} - -// Ensure that all typeDefinition types implements TypeDefinition interface -var _ TypeDefinition = (*ObjectTypeDefinition)(nil) -var _ TypeDefinition = (*InterfaceTypeDefinition)(nil) -var _ TypeDefinition = (*UnionTypeDefinition)(nil) -var _ TypeDefinition = (*ScalarTypeDefinition)(nil) -var _ TypeDefinition = (*EnumTypeDefinition)(nil) -var _ TypeDefinition = (*InputObjectTypeDefinition)(nil) -var _ TypeDefinition = (*TypeExtensionDefinition)(nil) - -// ObjectTypeDefinition implements Node, TypeDefinition -type ObjectTypeDefinition struct { +// Ensure that all typeDefinition types implements Definition interface +var _ Definition = (*ObjectDefinition)(nil) +var _ Definition = (*InterfaceDefinition)(nil) +var _ Definition = (*UnionDefinition)(nil) +var _ Definition = (*ScalarDefinition)(nil) +var _ Definition = (*EnumDefinition)(nil) +var _ Definition = (*InputObjectDefinition)(nil) +var _ Definition = (*TypeExtensionDefinition)(nil) + +// ObjectDefinition implements Node, Definition +type ObjectDefinition struct { Kind string Loc *Location Name *Name @@ -30,12 +22,12 @@ type ObjectTypeDefinition struct { Fields []*FieldDefinition } -func NewObjectTypeDefinition(def *ObjectTypeDefinition) *ObjectTypeDefinition { +func NewObjectDefinition(def *ObjectDefinition) *ObjectDefinition { if def == nil { - def = &ObjectTypeDefinition{} + def = &ObjectDefinition{} } - return &ObjectTypeDefinition{ - Kind: kinds.ObjectTypeDefinition, + return &ObjectDefinition{ + Kind: kinds.ObjectDefinition, Loc: def.Loc, Name: def.Name, Interfaces: def.Interfaces, @@ -43,27 +35,27 @@ func NewObjectTypeDefinition(def *ObjectTypeDefinition) *ObjectTypeDefinition { } } -func (def *ObjectTypeDefinition) GetKind() string { +func (def *ObjectDefinition) GetKind() string { return def.Kind } -func (def *ObjectTypeDefinition) GetLoc() *Location { +func (def *ObjectDefinition) GetLoc() *Location { return def.Loc } -func (def *ObjectTypeDefinition) GetName() *Name { +func (def *ObjectDefinition) GetName() *Name { return def.Name } -func (def *ObjectTypeDefinition) GetVariableDefinitions() []*VariableDefinition { +func (def *ObjectDefinition) GetVariableDefinitions() []*VariableDefinition { return []*VariableDefinition{} } -func (def *ObjectTypeDefinition) GetSelectionSet() *SelectionSet { +func (def *ObjectDefinition) GetSelectionSet() *SelectionSet { return &SelectionSet{} } -func (def *ObjectTypeDefinition) GetOperation() string { +func (def *ObjectDefinition) GetOperation() string { return "" } @@ -127,181 +119,181 @@ func (def *InputValueDefinition) GetLoc() *Location { return def.Loc } -// InterfaceTypeDefinition implements Node, TypeDefinition -type InterfaceTypeDefinition struct { +// InterfaceDefinition implements Node, Definition +type InterfaceDefinition struct { Kind string Loc *Location Name *Name Fields []*FieldDefinition } -func NewInterfaceTypeDefinition(def *InterfaceTypeDefinition) *InterfaceTypeDefinition { +func NewInterfaceTypeDefinition(def *InterfaceDefinition) *InterfaceDefinition { if def == nil { - def = &InterfaceTypeDefinition{} + def = &InterfaceDefinition{} } - return &InterfaceTypeDefinition{ - Kind: kinds.InterfaceTypeDefinition, + return &InterfaceDefinition{ + Kind: kinds.InterfaceDefinition, Loc: def.Loc, Name: def.Name, Fields: def.Fields, } } -func (def *InterfaceTypeDefinition) GetKind() string { +func (def *InterfaceDefinition) GetKind() string { return def.Kind } -func (def *InterfaceTypeDefinition) GetLoc() *Location { +func (def *InterfaceDefinition) GetLoc() *Location { return def.Loc } -func (def *InterfaceTypeDefinition) GetName() *Name { +func (def *InterfaceDefinition) GetName() *Name { return def.Name } -func (def *InterfaceTypeDefinition) GetVariableDefinitions() []*VariableDefinition { +func (def *InterfaceDefinition) GetVariableDefinitions() []*VariableDefinition { return []*VariableDefinition{} } -func (def *InterfaceTypeDefinition) GetSelectionSet() *SelectionSet { +func (def *InterfaceDefinition) GetSelectionSet() *SelectionSet { return &SelectionSet{} } -func (def *InterfaceTypeDefinition) GetOperation() string { +func (def *InterfaceDefinition) GetOperation() string { return "" } -// UnionTypeDefinition implements Node, TypeDefinition -type UnionTypeDefinition struct { +// UnionDefinition implements Node, Definition +type UnionDefinition struct { Kind string Loc *Location Name *Name Types []*NamedType } -func NewUnionTypeDefinition(def *UnionTypeDefinition) *UnionTypeDefinition { +func NewUnionTypeDefinition(def *UnionDefinition) *UnionDefinition { if def == nil { - def = &UnionTypeDefinition{} + def = &UnionDefinition{} } - return &UnionTypeDefinition{ - Kind: kinds.UnionTypeDefinition, + return &UnionDefinition{ + Kind: kinds.UnionDefinition, Loc: def.Loc, Name: def.Name, Types: def.Types, } } -func (def *UnionTypeDefinition) GetKind() string { +func (def *UnionDefinition) GetKind() string { return def.Kind } -func (def *UnionTypeDefinition) GetLoc() *Location { +func (def *UnionDefinition) GetLoc() *Location { return def.Loc } -func (def *UnionTypeDefinition) GetName() *Name { +func (def *UnionDefinition) GetName() *Name { return def.Name } -func (def *UnionTypeDefinition) GetVariableDefinitions() []*VariableDefinition { +func (def *UnionDefinition) GetVariableDefinitions() []*VariableDefinition { return []*VariableDefinition{} } -func (def *UnionTypeDefinition) GetSelectionSet() *SelectionSet { +func (def *UnionDefinition) GetSelectionSet() *SelectionSet { return &SelectionSet{} } -func (def *UnionTypeDefinition) GetOperation() string { +func (def *UnionDefinition) GetOperation() string { return "" } -// ScalarTypeDefinition implements Node, TypeDefinition -type ScalarTypeDefinition struct { +// ScalarDefinition implements Node, Definition +type ScalarDefinition struct { Kind string Loc *Location Name *Name } -func NewScalarTypeDefinition(def *ScalarTypeDefinition) *ScalarTypeDefinition { +func NewScalarTypeDefinition(def *ScalarDefinition) *ScalarDefinition { if def == nil { - def = &ScalarTypeDefinition{} + def = &ScalarDefinition{} } - return &ScalarTypeDefinition{ - Kind: kinds.ScalarTypeDefinition, + return &ScalarDefinition{ + Kind: kinds.ScalarDefinition, Loc: def.Loc, Name: def.Name, } } -func (def *ScalarTypeDefinition) GetKind() string { +func (def *ScalarDefinition) GetKind() string { return def.Kind } -func (def *ScalarTypeDefinition) GetLoc() *Location { +func (def *ScalarDefinition) GetLoc() *Location { return def.Loc } -func (def *ScalarTypeDefinition) GetName() *Name { +func (def *ScalarDefinition) GetName() *Name { return def.Name } -func (def *ScalarTypeDefinition) GetVariableDefinitions() []*VariableDefinition { +func (def *ScalarDefinition) GetVariableDefinitions() []*VariableDefinition { return []*VariableDefinition{} } -func (def *ScalarTypeDefinition) GetSelectionSet() *SelectionSet { +func (def *ScalarDefinition) GetSelectionSet() *SelectionSet { return &SelectionSet{} } -func (def *ScalarTypeDefinition) GetOperation() string { +func (def *ScalarDefinition) GetOperation() string { return "" } -// EnumTypeDefinition implements Node, TypeDefinition -type EnumTypeDefinition struct { +// EnumDefinition implements Node, Definition +type EnumDefinition struct { Kind string Loc *Location Name *Name Values []*EnumValueDefinition } -func NewEnumTypeDefinition(def *EnumTypeDefinition) *EnumTypeDefinition { +func NewEnumTypeDefinition(def *EnumDefinition) *EnumDefinition { if def == nil { - def = &EnumTypeDefinition{} + def = &EnumDefinition{} } - return &EnumTypeDefinition{ - Kind: kinds.EnumTypeDefinition, + return &EnumDefinition{ + Kind: kinds.EnumDefinition, Loc: def.Loc, Name: def.Name, Values: def.Values, } } -func (def *EnumTypeDefinition) GetKind() string { +func (def *EnumDefinition) GetKind() string { return def.Kind } -func (def *EnumTypeDefinition) GetLoc() *Location { +func (def *EnumDefinition) GetLoc() *Location { return def.Loc } -func (def *EnumTypeDefinition) GetName() *Name { +func (def *EnumDefinition) GetName() *Name { return def.Name } -func (def *EnumTypeDefinition) GetVariableDefinitions() []*VariableDefinition { +func (def *EnumDefinition) GetVariableDefinitions() []*VariableDefinition { return []*VariableDefinition{} } -func (def *EnumTypeDefinition) GetSelectionSet() *SelectionSet { +func (def *EnumDefinition) GetSelectionSet() *SelectionSet { return &SelectionSet{} } -func (def *EnumTypeDefinition) GetOperation() string { +func (def *EnumDefinition) GetOperation() string { return "" } -// EnumValueDefinition implements Node, TypeDefinition +// EnumValueDefinition implements Node, Definition type EnumValueDefinition struct { Kind string Loc *Location @@ -327,55 +319,55 @@ func (def *EnumValueDefinition) GetLoc() *Location { return def.Loc } -// InputObjectTypeDefinition implements Node, TypeDefinition -type InputObjectTypeDefinition struct { +// InputObjectDefinition implements Node, Definition +type InputObjectDefinition struct { Kind string Loc *Location Name *Name Fields []*InputValueDefinition } -func NewInputObjectTypeDefinition(def *InputObjectTypeDefinition) *InputObjectTypeDefinition { +func NewInputObjectTypeDefinition(def *InputObjectDefinition) *InputObjectDefinition { if def == nil { - def = &InputObjectTypeDefinition{} + def = &InputObjectDefinition{} } - return &InputObjectTypeDefinition{ - Kind: kinds.InputObjectTypeDefinition, + return &InputObjectDefinition{ + Kind: kinds.InputObjectDefinition, Loc: def.Loc, Name: def.Name, Fields: def.Fields, } } -func (def *InputObjectTypeDefinition) GetKind() string { +func (def *InputObjectDefinition) GetKind() string { return def.Kind } -func (def *InputObjectTypeDefinition) GetLoc() *Location { +func (def *InputObjectDefinition) GetLoc() *Location { return def.Loc } -func (def *InputObjectTypeDefinition) GetName() *Name { +func (def *InputObjectDefinition) GetName() *Name { return def.Name } -func (def *InputObjectTypeDefinition) GetVariableDefinitions() []*VariableDefinition { +func (def *InputObjectDefinition) GetVariableDefinitions() []*VariableDefinition { return []*VariableDefinition{} } -func (def *InputObjectTypeDefinition) GetSelectionSet() *SelectionSet { +func (def *InputObjectDefinition) GetSelectionSet() *SelectionSet { return &SelectionSet{} } -func (def *InputObjectTypeDefinition) GetOperation() string { +func (def *InputObjectDefinition) GetOperation() string { return "" } -// TypeExtensionDefinition implements Node, TypeDefinition +// TypeExtensionDefinition implements Node, Definition type TypeExtensionDefinition struct { Kind string Loc *Location - Definition *ObjectTypeDefinition + Definition *ObjectDefinition } func NewTypeExtensionDefinition(def *TypeExtensionDefinition) *TypeExtensionDefinition { diff --git a/language/ast/types.go b/language/ast/types.go index 3233ec3a..cdcb25a8 100644 --- a/language/ast/types.go +++ b/language/ast/types.go @@ -22,7 +22,7 @@ type NamedType struct { Name *Name } -func NewNamedType(t *NamedType) *NamedType { +func NewNamed(t *NamedType) *NamedType { if t == nil { t = &NamedType{} } diff --git a/language/kinds/kinds.go b/language/kinds/kinds.go index c8b66b32..9de9e9f2 100644 --- a/language/kinds/kinds.go +++ b/language/kinds/kinds.go @@ -25,14 +25,14 @@ const ( ListValue = "ListValue" ObjectValue = "ObjectValue" ObjectField = "ObjectField" - ObjectTypeDefinition = "ObjectTypeDefinition" + ObjectDefinition = "ObjectDefinition" FieldDefinition = "FieldDefinition" InputValueDefinition = "InputValueDefinition" - InterfaceTypeDefinition = "InterfaceTypeDefinition" - UnionTypeDefinition = "UnionTypeDefinition" - ScalarTypeDefinition = "ScalarTypeDefinition" - EnumTypeDefinition = "EnumTypeDefinition" + InterfaceDefinition = "InterfaceDefinition" + UnionDefinition = "UnionDefinition" + ScalarDefinition = "ScalarDefinition" + EnumDefinition = "EnumDefinition" EnumValueDefinition = "EnumValueDefinition" - InputObjectTypeDefinition = "InputObjectTypeDefinition" + InputObjectDefinition = "InputObjectDefinition" TypeExtensionDefinition = "TypeExtensionDefinition" ) diff --git a/language/parser/parser.go b/language/parser/parser.go index 6cadd34a..c8de4335 100644 --- a/language/parser/parser.go +++ b/language/parser/parser.go @@ -720,7 +720,7 @@ func parseNamedType(parser *Parser) (*ast.NamedType, error) { if err != nil { return nil, err } - return ast.NewNamedType(&ast.NamedType{ + return ast.NewNamed(&ast.NamedType{ Name: name, Loc: loc(parser, start), }), nil @@ -728,7 +728,7 @@ func parseNamedType(parser *Parser) (*ast.NamedType, error) { /* Implements the parsing rules in the Type Definition section. */ -func parseObjectTypeDefinition(parser *Parser) (*ast.ObjectTypeDefinition, error) { +func parseObjectTypeDefinition(parser *Parser) (*ast.ObjectDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "type") if err != nil { @@ -752,7 +752,7 @@ func parseObjectTypeDefinition(parser *Parser) (*ast.ObjectTypeDefinition, error fields = append(fields, iField.(*ast.FieldDefinition)) } } - return ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + return ast.NewObjectDefinition(&ast.ObjectDefinition{ Name: name, Loc: loc(parser, start), Interfaces: interfaces, @@ -854,7 +854,7 @@ func parseInputValueDef(parser *Parser) (interface{}, error) { }), nil } -func parseInterfaceTypeDefinition(parser *Parser) (*ast.InterfaceTypeDefinition, error) { +func parseInterfaceTypeDefinition(parser *Parser) (*ast.InterfaceDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "interface") if err != nil { @@ -874,14 +874,14 @@ func parseInterfaceTypeDefinition(parser *Parser) (*ast.InterfaceTypeDefinition, fields = append(fields, iField.(*ast.FieldDefinition)) } } - return ast.NewInterfaceTypeDefinition(&ast.InterfaceTypeDefinition{ + return ast.NewInterfaceTypeDefinition(&ast.InterfaceDefinition{ Name: name, Loc: loc(parser, start), Fields: fields, }), nil } -func parseUnionTypeDefinition(parser *Parser) (*ast.UnionTypeDefinition, error) { +func parseUnionTypeDefinition(parser *Parser) (*ast.UnionDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "union") if err != nil { @@ -899,7 +899,7 @@ func parseUnionTypeDefinition(parser *Parser) (*ast.UnionTypeDefinition, error) if err != nil { return nil, err } - return ast.NewUnionTypeDefinition(&ast.UnionTypeDefinition{ + return ast.NewUnionTypeDefinition(&ast.UnionDefinition{ Name: name, Loc: loc(parser, start), Types: types, @@ -921,7 +921,7 @@ func parseUnionMembers(parser *Parser) ([]*ast.NamedType, error) { return members, nil } -func parseScalarTypeDefinition(parser *Parser) (*ast.ScalarTypeDefinition, error) { +func parseScalarTypeDefinition(parser *Parser) (*ast.ScalarDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "scalar") if err != nil { @@ -931,14 +931,14 @@ func parseScalarTypeDefinition(parser *Parser) (*ast.ScalarTypeDefinition, error if err != nil { return nil, err } - def := ast.NewScalarTypeDefinition(&ast.ScalarTypeDefinition{ + def := ast.NewScalarTypeDefinition(&ast.ScalarDefinition{ Name: name, Loc: loc(parser, start), }) return def, nil } -func parseEnumTypeDefinition(parser *Parser) (*ast.EnumTypeDefinition, error) { +func parseEnumTypeDefinition(parser *Parser) (*ast.EnumDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "enum") if err != nil { @@ -958,7 +958,7 @@ func parseEnumTypeDefinition(parser *Parser) (*ast.EnumTypeDefinition, error) { values = append(values, iEnumValueDef.(*ast.EnumValueDefinition)) } } - return ast.NewEnumTypeDefinition(&ast.EnumTypeDefinition{ + return ast.NewEnumTypeDefinition(&ast.EnumDefinition{ Name: name, Loc: loc(parser, start), Values: values, @@ -977,7 +977,7 @@ func parseEnumValueDefinition(parser *Parser) (interface{}, error) { }), nil } -func parseInputObjectTypeDefinition(parser *Parser) (*ast.InputObjectTypeDefinition, error) { +func parseInputObjectTypeDefinition(parser *Parser) (*ast.InputObjectDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "input") if err != nil { @@ -997,7 +997,7 @@ func parseInputObjectTypeDefinition(parser *Parser) (*ast.InputObjectTypeDefinit fields = append(fields, iInputValueDefinition.(*ast.InputValueDefinition)) } } - return ast.NewInputObjectTypeDefinition(&ast.InputObjectTypeDefinition{ + return ast.NewInputObjectTypeDefinition(&ast.InputObjectDefinition{ Name: name, Loc: loc(parser, start), Fields: fields, diff --git a/language/parser/parser_test.go b/language/parser/parser_test.go index a708072a..ec45324c 100644 --- a/language/parser/parser_test.go +++ b/language/parser/parser_test.go @@ -78,7 +78,7 @@ func TestParseProvidesUsefulErrors(t *testing.T) { } _, err := Parse(params) - expectedError := &graphqlerrors.GraphQLError{ + expectedError := &graphqlerrors.Error{ Message: `Syntax Error GraphQL (1:2) Expected Name, found EOF 1: { @@ -87,7 +87,7 @@ func TestParseProvidesUsefulErrors(t *testing.T) { Positions: []int{1}, Locations: []location.SourceLocation{{1, 2}}, } - checkGraphQLError(t, err, expectedError) + checkError(t, err, expectedError) testErrorMessagesTable := []errorMessageTest{ { @@ -118,7 +118,7 @@ fragment MissingOn Type t.Skipf("Skipped test: %v", test.source) } _, err := Parse(ParseParams{Source: test.source}) - checkGraphQLErrorMessage(t, err, test.expectedMessage) + checkErrorMessage(t, err, test.expectedMessage) } } @@ -129,7 +129,7 @@ func TestParseProvidesUsefulErrorsWhenUsingSource(t *testing.T) { `Syntax Error MyQuery.graphql (1:6) Expected Name, found EOF`, false, } - testGraphQLErrorMessage(t, test) + testErrorMessage(t, test) } func TestParsesVariableInlineValues(t *testing.T) { @@ -147,7 +147,7 @@ func TestParsesConstantDefaultValues(t *testing.T) { `Syntax Error GraphQL (1:37) Unexpected $`, false, } - testGraphQLErrorMessage(t, test) + testErrorMessage(t, test) } func TestDuplicatedKeysInInputObject(t *testing.T) { @@ -156,7 +156,7 @@ func TestDuplicatedKeysInInputObject(t *testing.T) { `Syntax Error GraphQL (1:22) Duplicate input object field a.`, false, } - testGraphQLErrorMessage(t, test) + testErrorMessage(t, test) } func TestDoesNotAcceptFragmentsNameOn(t *testing.T) { @@ -165,7 +165,7 @@ func TestDoesNotAcceptFragmentsNameOn(t *testing.T) { `Syntax Error GraphQL (1:10) Unexpected Name "on"`, false, } - testGraphQLErrorMessage(t, test) + testErrorMessage(t, test) } func TestDoesNotAcceptFragmentsSpreadOfOn(t *testing.T) { @@ -174,7 +174,7 @@ func TestDoesNotAcceptFragmentsSpreadOfOn(t *testing.T) { `Syntax Error GraphQL (1:9) Expected Name, found }`, false, } - testGraphQLErrorMessage(t, test) + testErrorMessage(t, test) } func TestDoesNotAllowNullAsValue(t *testing.T) { @@ -183,7 +183,7 @@ func TestDoesNotAllowNullAsValue(t *testing.T) { `Syntax Error GraphQL (1:39) Unexpected Name "null"`, false, } - testGraphQLErrorMessage(t, test) + testErrorMessage(t, test) } func TestParsesKitchenSink(t *testing.T) { @@ -371,15 +371,15 @@ type errorMessageTest struct { skipped bool } -func testGraphQLErrorMessage(t *testing.T, test errorMessageTest) { +func testErrorMessage(t *testing.T, test errorMessageTest) { if test.skipped != false { t.Skipf("Skipped test: %v", test.source) } _, err := Parse(ParseParams{Source: test.source}) - checkGraphQLErrorMessage(t, err, test.expectedMessage) + checkErrorMessage(t, err, test.expectedMessage) } -func checkGraphQLError(t *testing.T, err error, expectedError *graphqlerrors.GraphQLError) { +func checkError(t *testing.T, err error, expectedError *graphqlerrors.Error) { if expectedError == nil { if err != nil { t.Fatalf("unexpected error: %v", err) @@ -393,19 +393,19 @@ func checkGraphQLError(t *testing.T, err error, expectedError *graphqlerrors.Gra if err.Error() != expectedError.Message { t.Fatalf("unexpected error.\nexpected:\n%v\n\ngot:\n%v", expectedError, err.Error()) } - gErr := toGraphQLError(err) + gErr := toError(err) if gErr == nil { - t.Fatalf("unexpected nil GraphQLError") + t.Fatalf("unexpected nil Error") } if len(expectedError.Positions) > 0 && !reflect.DeepEqual(gErr.Positions, expectedError.Positions) { - t.Fatalf("unexpected GraphQLError.Positions.\nexpected:\n%v\n\ngot:\n%v", expectedError.Positions, gErr.Positions) + t.Fatalf("unexpected Error.Positions.\nexpected:\n%v\n\ngot:\n%v", expectedError.Positions, gErr.Positions) } if len(expectedError.Locations) > 0 && !reflect.DeepEqual(gErr.Locations, expectedError.Locations) { - t.Fatalf("unexpected GraphQLError.Locations.\nexpected:\n%v\n\ngot:\n%v", expectedError.Locations, gErr.Locations) + t.Fatalf("unexpected Error.Locations.\nexpected:\n%v\n\ngot:\n%v", expectedError.Locations, gErr.Locations) } } -func checkGraphQLErrorMessage(t *testing.T, err error, expectedMessage string) { +func checkErrorMessage(t *testing.T, err error, expectedMessage string) { if err == nil { t.Fatalf("unexpected nil error\nexpected:\n%v\n\ngot:\n%v", expectedMessage, err) } @@ -418,12 +418,12 @@ func checkGraphQLErrorMessage(t *testing.T, err error, expectedMessage string) { } } -func toGraphQLError(err error) *graphqlerrors.GraphQLError { +func toError(err error) *graphqlerrors.Error { if err == nil { return nil } switch err := err.(type) { - case *graphqlerrors.GraphQLError: + case *graphqlerrors.Error: return err default: return nil diff --git a/language/parser/schema_parser_test.go b/language/parser/schema_parser_test.go index 4f5f4007..d431fed0 100644 --- a/language/parser/schema_parser_test.go +++ b/language/parser/schema_parser_test.go @@ -39,7 +39,7 @@ type Hello { expected := ast.NewDocument(&ast.Document{ Loc: loc(1, 31), Definitions: []ast.Node{ - ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: loc(1, 31), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -54,7 +54,7 @@ type Hello { Loc: loc(16, 21), }), Arguments: []*ast.InputValueDefinition{}, - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(23, 29), Name: ast.NewName(&ast.Name{ Value: "String", @@ -83,7 +83,7 @@ extend type Hello { Definitions: []ast.Node{ ast.NewTypeExtensionDefinition(&ast.TypeExtensionDefinition{ Loc: loc(1, 38), - Definition: ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + Definition: ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: loc(8, 38), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -98,7 +98,7 @@ extend type Hello { Loc: loc(23, 28), }), Arguments: []*ast.InputValueDefinition{}, - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(30, 36), Name: ast.NewName(&ast.Name{ Value: "String", @@ -126,7 +126,7 @@ type Hello { expected := ast.NewDocument(&ast.Document{ Loc: loc(1, 32), Definitions: []ast.Node{ - ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: loc(1, 32), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -144,7 +144,7 @@ type Hello { Type: ast.NewNonNullType(&ast.NonNullType{ Kind: "NonNullType", Loc: loc(23, 30), - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(23, 29), Name: ast.NewName(&ast.Name{ Value: "String", @@ -168,14 +168,14 @@ func TestSchemaParser_SimpleTypeInheritingInterface(t *testing.T) { expected := ast.NewDocument(&ast.Document{ Loc: loc(0, 31), Definitions: []ast.Node{ - ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: loc(0, 31), Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: loc(5, 10), }), Interfaces: []*ast.NamedType{ - ast.NewNamedType(&ast.NamedType{ + ast.NewNamed(&ast.NamedType{ Name: ast.NewName(&ast.Name{ Value: "World", Loc: loc(22, 27), @@ -198,21 +198,21 @@ func TestSchemaParser_SimpleTypeInheritingMultipleInterfaces(t *testing.T) { expected := ast.NewDocument(&ast.Document{ Loc: loc(0, 33), Definitions: []ast.Node{ - ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: loc(0, 33), Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: loc(5, 10), }), Interfaces: []*ast.NamedType{ - ast.NewNamedType(&ast.NamedType{ + ast.NewNamed(&ast.NamedType{ Name: ast.NewName(&ast.Name{ Value: "Wo", Loc: loc(22, 24), }), Loc: loc(22, 24), }), - ast.NewNamedType(&ast.NamedType{ + ast.NewNamed(&ast.NamedType{ Name: ast.NewName(&ast.Name{ Value: "rld", Loc: loc(26, 29), @@ -235,7 +235,7 @@ func TestSchemaParser_SingleValueEnum(t *testing.T) { expected := ast.NewDocument(&ast.Document{ Loc: loc(0, 20), Definitions: []ast.Node{ - ast.NewEnumTypeDefinition(&ast.EnumTypeDefinition{ + ast.NewEnumTypeDefinition(&ast.EnumDefinition{ Loc: loc(0, 20), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -264,7 +264,7 @@ func TestSchemaParser_DoubleValueEnum(t *testing.T) { expected := ast.NewDocument(&ast.Document{ Loc: loc(0, 22), Definitions: []ast.Node{ - ast.NewEnumTypeDefinition(&ast.EnumTypeDefinition{ + ast.NewEnumTypeDefinition(&ast.EnumDefinition{ Loc: loc(0, 22), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -303,7 +303,7 @@ interface Hello { expected := ast.NewDocument(&ast.Document{ Loc: loc(1, 36), Definitions: []ast.Node{ - ast.NewInterfaceTypeDefinition(&ast.InterfaceTypeDefinition{ + ast.NewInterfaceTypeDefinition(&ast.InterfaceDefinition{ Loc: loc(1, 36), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -317,7 +317,7 @@ interface Hello { Loc: loc(21, 26), }), Arguments: []*ast.InputValueDefinition{}, - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(28, 34), Name: ast.NewName(&ast.Name{ Value: "String", @@ -343,7 +343,7 @@ type Hello { expected := ast.NewDocument(&ast.Document{ Loc: loc(1, 46), Definitions: []ast.Node{ - ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: loc(1, 46), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -364,7 +364,7 @@ type Hello { Value: "flag", Loc: loc(22, 26), }), - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(28, 35), Name: ast.NewName(&ast.Name{ Value: "Boolean", @@ -374,7 +374,7 @@ type Hello { DefaultValue: nil, }), }, - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(38, 44), Name: ast.NewName(&ast.Name{ Value: "String", @@ -400,7 +400,7 @@ type Hello { expected := ast.NewDocument(&ast.Document{ Loc: loc(1, 53), Definitions: []ast.Node{ - ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: loc(1, 53), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -421,7 +421,7 @@ type Hello { Value: "flag", Loc: loc(22, 26), }), - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(28, 35), Name: ast.NewName(&ast.Name{ Value: "Boolean", @@ -434,7 +434,7 @@ type Hello { }), }), }, - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(45, 51), Name: ast.NewName(&ast.Name{ Value: "String", @@ -460,7 +460,7 @@ type Hello { expected := ast.NewDocument(&ast.Document{ Loc: loc(1, 49), Definitions: []ast.Node{ - ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: loc(1, 49), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -483,7 +483,7 @@ type Hello { }), Type: ast.NewListType(&ast.ListType{ Loc: loc(30, 38), - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(31, 37), Name: ast.NewName(&ast.Name{ Value: "String", @@ -494,7 +494,7 @@ type Hello { DefaultValue: nil, }), }, - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(41, 47), Name: ast.NewName(&ast.Name{ Value: "String", @@ -520,7 +520,7 @@ type Hello { expected := ast.NewDocument(&ast.Document{ Loc: loc(1, 61), Definitions: []ast.Node{ - ast.NewObjectTypeDefinition(&ast.ObjectTypeDefinition{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: loc(1, 61), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -541,7 +541,7 @@ type Hello { Value: "argOne", Loc: loc(22, 28), }), - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(30, 37), Name: ast.NewName(&ast.Name{ Value: "Boolean", @@ -556,7 +556,7 @@ type Hello { Value: "argTwo", Loc: loc(39, 45), }), - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(47, 50), Name: ast.NewName(&ast.Name{ Value: "Int", @@ -566,7 +566,7 @@ type Hello { DefaultValue: nil, }), }, - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(53, 59), Name: ast.NewName(&ast.Name{ Value: "String", @@ -589,14 +589,14 @@ func TestSchemaParser_SimpleUnion(t *testing.T) { expected := ast.NewDocument(&ast.Document{ Loc: loc(0, 19), Definitions: []ast.Node{ - ast.NewUnionTypeDefinition(&ast.UnionTypeDefinition{ + ast.NewUnionTypeDefinition(&ast.UnionDefinition{ Loc: loc(0, 19), Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: loc(6, 11), }), Types: []*ast.NamedType{ - ast.NewNamedType(&ast.NamedType{ + ast.NewNamed(&ast.NamedType{ Loc: loc(14, 19), Name: ast.NewName(&ast.Name{ Value: "World", @@ -618,21 +618,21 @@ func TestSchemaParser_UnionWithTwoTypes(t *testing.T) { expected := ast.NewDocument(&ast.Document{ Loc: loc(0, 22), Definitions: []ast.Node{ - ast.NewUnionTypeDefinition(&ast.UnionTypeDefinition{ + ast.NewUnionTypeDefinition(&ast.UnionDefinition{ Loc: loc(0, 22), Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: loc(6, 11), }), Types: []*ast.NamedType{ - ast.NewNamedType(&ast.NamedType{ + ast.NewNamed(&ast.NamedType{ Loc: loc(14, 16), Name: ast.NewName(&ast.Name{ Value: "Wo", Loc: loc(14, 16), }), }), - ast.NewNamedType(&ast.NamedType{ + ast.NewNamed(&ast.NamedType{ Loc: loc(19, 22), Name: ast.NewName(&ast.Name{ Value: "Rld", @@ -654,7 +654,7 @@ func TestSchemaParser_Scalar(t *testing.T) { expected := ast.NewDocument(&ast.Document{ Loc: loc(0, 12), Definitions: []ast.Node{ - ast.NewScalarTypeDefinition(&ast.ScalarTypeDefinition{ + ast.NewScalarTypeDefinition(&ast.ScalarDefinition{ Loc: loc(0, 12), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -677,7 +677,7 @@ input Hello { expected := ast.NewDocument(&ast.Document{ Loc: loc(1, 32), Definitions: []ast.Node{ - ast.NewInputObjectTypeDefinition(&ast.InputObjectTypeDefinition{ + ast.NewInputObjectTypeDefinition(&ast.InputObjectDefinition{ Loc: loc(1, 32), Name: ast.NewName(&ast.Name{ Value: "Hello", @@ -690,7 +690,7 @@ input Hello { Value: "world", Loc: loc(17, 22), }), - Type: ast.NewNamedType(&ast.NamedType{ + Type: ast.NewNamed(&ast.NamedType{ Loc: loc(24, 30), Name: ast.NewName(&ast.Name{ Value: "String", @@ -722,7 +722,7 @@ input Hello { }, }) - expectedError := &graphqlerrors.GraphQLError{ + expectedError := &graphqlerrors.Error{ Message: `Syntax Error GraphQL (3:8) Expected :, found ( 2: input Hello { diff --git a/language/printer/printer.go b/language/printer/printer.go index b2baacf7..0f04a483 100644 --- a/language/printer/printer.go +++ b/language/printer/printer.go @@ -325,7 +325,7 @@ var printDocASTReducer = map[string]visitor.VisitFunc{ return visitor.ActionNoChange, nil }, - "ObjectTypeDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "ObjectDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") @@ -358,7 +358,7 @@ var printDocASTReducer = map[string]visitor.VisitFunc{ } return visitor.ActionNoChange, nil }, - "InterfaceTypeDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "InterfaceDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") @@ -368,7 +368,7 @@ var printDocASTReducer = map[string]visitor.VisitFunc{ } return visitor.ActionNoChange, nil }, - "UnionTypeDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "UnionDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") @@ -378,7 +378,7 @@ var printDocASTReducer = map[string]visitor.VisitFunc{ } return visitor.ActionNoChange, nil }, - "ScalarTypeDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "ScalarDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") @@ -387,7 +387,7 @@ var printDocASTReducer = map[string]visitor.VisitFunc{ } return visitor.ActionNoChange, nil }, - "EnumTypeDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "EnumDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") @@ -405,7 +405,7 @@ var printDocASTReducer = map[string]visitor.VisitFunc{ } return visitor.ActionNoChange, nil }, - "InputObjectTypeDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "InputObjectDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") diff --git a/language/printer/schema_printer_test.go b/language/printer/schema_printer_test.go index bb73af3e..4d91a10e 100644 --- a/language/printer/schema_printer_test.go +++ b/language/printer/schema_printer_test.go @@ -10,7 +10,7 @@ import ( ) func TestSchemaPrinter_PrintsMinimalAST(t *testing.T) { - astDoc := ast.NewScalarTypeDefinition(&ast.ScalarTypeDefinition{ + astDoc := ast.NewScalarTypeDefinition(&ast.ScalarDefinition{ Name: ast.NewName(&ast.Name{ Value: "foo", }), diff --git a/language/visitor/visitor.go b/language/visitor/visitor.go index cff392a6..8cb8107b 100644 --- a/language/visitor/visitor.go +++ b/language/visitor/visitor.go @@ -81,7 +81,7 @@ var QueryDocumentKeys KeyMap = KeyMap{ "ListType": []string{"Type"}, "NonNullType": []string{"Type"}, - "ObjectTypeDefinition": []string{ + "ObjectDefinition": []string{ "Name", "Interfaces", "Fields", @@ -96,21 +96,21 @@ var QueryDocumentKeys KeyMap = KeyMap{ "Type", "DefaultValue", }, - "InterfaceTypeDefinition": []string{ + "InterfaceDefinition": []string{ "Name", "Fields", }, - "UnionTypeDefinition": []string{ + "UnionDefinition": []string{ "Name", "Types", }, - "ScalarTypeDefinition": []string{"Name"}, - "EnumTypeDefinition": []string{ + "ScalarDefinition": []string{"Name"}, + "EnumDefinition": []string{ "Name", "Values", }, "EnumValueDefinition": []string{"Name"}, - "InputObjectTypeDefinition": []string{ + "InputObjectDefinition": []string{ "Name", "Fields", }, diff --git a/testutil/testutil.go b/testutil/testutil.go index 57ae13c8..f9bb706c 100644 --- a/testutil/testutil.go +++ b/testutil/testutil.go @@ -23,10 +23,10 @@ var ( Artoo StarWarsChar HumanData map[int]StarWarsChar DroidData map[int]StarWarsChar - StarWarsSchema types.GraphQLSchema + StarWarsSchema types.Schema - humanType *types.GraphQLObjectType - droidType *types.GraphQLObjectType + humanType *types.Object + droidType *types.Object ) type StarWarsChar struct { @@ -98,43 +98,43 @@ func init() { 2001: Artoo, } - episodeEnum := types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ + episodeEnum := types.NewEnum(types.EnumConfig{ Name: "Episode", Description: "One of the films in the Star Wars Trilogy", - Values: types.GraphQLEnumValueConfigMap{ - "NEWHOPE": &types.GraphQLEnumValueConfig{ + Values: types.EnumValueConfigMap{ + "NEWHOPE": &types.EnumValueConfig{ Value: 4, Description: "Released in 1977.", }, - "EMPIRE": &types.GraphQLEnumValueConfig{ + "EMPIRE": &types.EnumValueConfig{ Value: 5, Description: "Released in 1980.", }, - "JEDI": &types.GraphQLEnumValueConfig{ + "JEDI": &types.EnumValueConfig{ Value: 6, Description: "Released in 1983.", }, }, }) - characterInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + characterInterface := types.NewInterface(types.InterfaceConfig{ Name: "Character", Description: "A character in the Star Wars Trilogy", - Fields: types.GraphQLFieldConfigMap{ - "id": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(types.GraphQLString), + Fields: types.FieldConfigMap{ + "id": &types.FieldConfig{ + Type: types.NewNonNull(types.String), Description: "The id of the character.", }, - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "name": &types.FieldConfig{ + Type: types.String, Description: "The name of the character.", }, - "appearsIn": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(episodeEnum), + "appearsIn": &types.FieldConfig{ + Type: types.NewList(episodeEnum), Description: "Which movies they appear in.", }, }, - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { if character, ok := value.(StarWarsChar); ok { id, _ := strconv.Atoi(character.Id) human := GetHuman(id) @@ -145,17 +145,17 @@ func init() { return droidType }, }) - characterInterface.AddFieldConfig("friends", &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(characterInterface), + characterInterface.AddFieldConfig("friends", &types.FieldConfig{ + Type: types.NewList(characterInterface), Description: "The friends of the character, or an empty list if they have none.", }) - humanType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + humanType = types.NewObject(types.ObjectConfig{ Name: "Human", Description: "A humanoid creature in the Star Wars universe.", - Fields: types.GraphQLFieldConfigMap{ - "id": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(types.GraphQLString), + Fields: types.FieldConfigMap{ + "id": &types.FieldConfig{ + Type: types.NewNonNull(types.String), Description: "The id of the human.", Resolve: func(p types.GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { @@ -164,8 +164,8 @@ func init() { return nil }, }, - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "name": &types.FieldConfig{ + Type: types.String, Description: "The name of the human.", Resolve: func(p types.GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { @@ -174,8 +174,8 @@ func init() { return nil }, }, - "friends": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(characterInterface), + "friends": &types.FieldConfig{ + Type: types.NewList(characterInterface), Description: "The friends of the human, or an empty list if they have none.", Resolve: func(p types.GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { @@ -184,8 +184,8 @@ func init() { return []interface{}{} }, }, - "appearsIn": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(episodeEnum), + "appearsIn": &types.FieldConfig{ + Type: types.NewList(episodeEnum), Description: "Which movies they appear in.", Resolve: func(p types.GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { @@ -194,8 +194,8 @@ func init() { return nil }, }, - "homePlanet": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "homePlanet": &types.FieldConfig{ + Type: types.String, Description: "The home planet of the human, or null if unknown.", Resolve: func(p types.GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { @@ -205,16 +205,16 @@ func init() { }, }, }, - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ characterInterface, }, }) - droidType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + droidType = types.NewObject(types.ObjectConfig{ Name: "Droid", Description: "A mechanical creature in the Star Wars universe.", - Fields: types.GraphQLFieldConfigMap{ - "id": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(types.GraphQLString), + Fields: types.FieldConfigMap{ + "id": &types.FieldConfig{ + Type: types.NewNonNull(types.String), Description: "The id of the droid.", Resolve: func(p types.GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { @@ -223,8 +223,8 @@ func init() { return nil }, }, - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "name": &types.FieldConfig{ + Type: types.String, Description: "The name of the droid.", Resolve: func(p types.GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { @@ -233,8 +233,8 @@ func init() { return nil }, }, - "friends": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(characterInterface), + "friends": &types.FieldConfig{ + Type: types.NewList(characterInterface), Description: "The friends of the droid, or an empty list if they have none.", Resolve: func(p types.GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { @@ -250,8 +250,8 @@ func init() { return []interface{}{} }, }, - "appearsIn": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(episodeEnum), + "appearsIn": &types.FieldConfig{ + Type: types.NewList(episodeEnum), Description: "Which movies they appear in.", Resolve: func(p types.GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { @@ -260,8 +260,8 @@ func init() { return nil }, }, - "primaryFunction": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "primaryFunction": &types.FieldConfig{ + Type: types.String, Description: "The primary function of the droid.", Resolve: func(p types.GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { @@ -271,18 +271,18 @@ func init() { }, }, }, - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ characterInterface, }, }) - queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + queryType := types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "hero": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "hero": &types.FieldConfig{ Type: characterInterface, - Args: types.GraphQLFieldConfigArgumentMap{ - "episode": &types.GraphQLArgumentConfig{ + Args: types.FieldConfigArgument{ + "episode": &types.ArgumentConfig{ Description: "If omitted, returns the hero of the whole saga. If " + "provided, returns the hero of that particular episode.", Type: episodeEnum, @@ -292,24 +292,24 @@ func init() { return GetHero(p.Args["episode"]) }, }, - "human": &types.GraphQLFieldConfig{ + "human": &types.FieldConfig{ Type: humanType, - Args: types.GraphQLFieldConfigArgumentMap{ - "id": &types.GraphQLArgumentConfig{ + Args: types.FieldConfigArgument{ + "id": &types.ArgumentConfig{ Description: "id of the human", - Type: types.NewGraphQLNonNull(types.GraphQLString), + Type: types.NewNonNull(types.String), }, }, Resolve: func(p types.GQLFRParams) (r interface{}) { return GetHuman(p.Args["id"].(int)) }, }, - "droid": &types.GraphQLFieldConfig{ + "droid": &types.FieldConfig{ Type: droidType, - Args: types.GraphQLFieldConfigArgumentMap{ - "id": &types.GraphQLArgumentConfig{ + Args: types.FieldConfigArgument{ + "id": &types.ArgumentConfig{ Description: "id of the droid", - Type: types.NewGraphQLNonNull(types.GraphQLString), + Type: types.NewNonNull(types.String), }, }, Resolve: func(p types.GQLFRParams) (r interface{}) { @@ -318,7 +318,7 @@ func init() { }, }, }) - StarWarsSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + StarWarsSchema, _ = types.NewSchema(types.SchemaConfig{ Query: queryType, }) } @@ -357,8 +357,8 @@ func Parse(t *testing.T, query string) *ast.Document { } return astDoc } -func Execute(t *testing.T, ep executor.ExecuteParams) *types.GraphQLResult { - resultChannel := make(chan *types.GraphQLResult) +func Execute(t *testing.T, ep executor.ExecuteParams) *types.Result { + resultChannel := make(chan *types.Result) go executor.Execute(ep, resultChannel) result := <-resultChannel return result diff --git a/types/definition.go b/types/definition.go index 7f8e6c7e..f5ee884c 100644 --- a/types/definition.go +++ b/types/definition.go @@ -11,126 +11,126 @@ import ( ) // These are all of the possible kinds of types. -type GraphQLType interface { +type Type interface { GetName() string GetDescription() string String() string GetError() error } -var _ GraphQLType = (*GraphQLScalarType)(nil) -var _ GraphQLType = (*GraphQLObjectType)(nil) -var _ GraphQLType = (*GraphQLInterfaceType)(nil) -var _ GraphQLType = (*GraphQLUnionType)(nil) -var _ GraphQLType = (*GraphQLEnumType)(nil) -var _ GraphQLType = (*GraphQLInputObjectType)(nil) -var _ GraphQLType = (*GraphQLList)(nil) -var _ GraphQLType = (*GraphQLNonNull)(nil) -var _ GraphQLType = (*GraphQLArgument)(nil) +var _ Type = (*Scalar)(nil) +var _ Type = (*Object)(nil) +var _ Type = (*Interface)(nil) +var _ Type = (*Union)(nil) +var _ Type = (*Enum)(nil) +var _ Type = (*InputObject)(nil) +var _ Type = (*List)(nil) +var _ Type = (*NonNull)(nil) +var _ Type = (*Argument)(nil) // These types may be used as input types for arguments and directives. -type GraphQLInputType interface { +type Input interface { GetName() string GetDescription() string String() string GetError() error } -var _ GraphQLInputType = (*GraphQLScalarType)(nil) -var _ GraphQLInputType = (*GraphQLEnumType)(nil) -var _ GraphQLInputType = (*GraphQLInputObjectType)(nil) -var _ GraphQLInputType = (*GraphQLList)(nil) -var _ GraphQLInputType = (*GraphQLNonNull)(nil) +var _ Input = (*Scalar)(nil) +var _ Input = (*Enum)(nil) +var _ Input = (*InputObject)(nil) +var _ Input = (*List)(nil) +var _ Input = (*NonNull)(nil) -func IsInputType(ttype GraphQLType) bool { +func IsInputType(ttype Type) bool { namedType := GetNamedType(ttype) - if _, ok := namedType.(*GraphQLScalarType); ok { + if _, ok := namedType.(*Scalar); ok { return true } - if _, ok := namedType.(*GraphQLEnumType); ok { + if _, ok := namedType.(*Enum); ok { return true } - if _, ok := namedType.(*GraphQLInputObjectType); ok { + if _, ok := namedType.(*InputObject); ok { return true } return false } -func IsOutputType(ttype GraphQLType) bool { +func IsOutputType(ttype Type) bool { namedType := GetNamedType(ttype) - if _, ok := namedType.(*GraphQLScalarType); ok { + if _, ok := namedType.(*Scalar); ok { return true } - if _, ok := namedType.(*GraphQLObjectType); ok { + if _, ok := namedType.(*Object); ok { return true } - if _, ok := namedType.(*GraphQLInterfaceType); ok { + if _, ok := namedType.(*Interface); ok { return true } - if _, ok := namedType.(*GraphQLUnionType); ok { + if _, ok := namedType.(*Union); ok { return true } - if _, ok := namedType.(*GraphQLEnumType); ok { + if _, ok := namedType.(*Enum); ok { return true } return false } // These types may be used as output types as the result of fields. -type GraphQLOutputType interface { +type Output interface { GetName() string GetDescription() string String() string GetError() error } -var _ GraphQLOutputType = (*GraphQLScalarType)(nil) -var _ GraphQLOutputType = (*GraphQLObjectType)(nil) -var _ GraphQLOutputType = (*GraphQLInterfaceType)(nil) -var _ GraphQLOutputType = (*GraphQLUnionType)(nil) -var _ GraphQLOutputType = (*GraphQLEnumType)(nil) -var _ GraphQLOutputType = (*GraphQLList)(nil) -var _ GraphQLOutputType = (*GraphQLNonNull)(nil) +var _ Output = (*Scalar)(nil) +var _ Output = (*Object)(nil) +var _ Output = (*Interface)(nil) +var _ Output = (*Union)(nil) +var _ Output = (*Enum)(nil) +var _ Output = (*List)(nil) +var _ Output = (*NonNull)(nil) // These types may describe the parent context of a selection set. -type GraphQLCompositeType interface { +type Composite interface { GetName() string } -var _ GraphQLCompositeType = (*GraphQLObjectType)(nil) -var _ GraphQLCompositeType = (*GraphQLInterfaceType)(nil) -var _ GraphQLCompositeType = (*GraphQLUnionType)(nil) +var _ Composite = (*Object)(nil) +var _ Composite = (*Interface)(nil) +var _ Composite = (*Union)(nil) // These types may describe the parent context of a selection set. -type GraphQLAbstractType interface { - GetObjectType(value interface{}, info GraphQLResolveInfo) *GraphQLObjectType - GetPossibleTypes() []*GraphQLObjectType - IsPossibleType(ttype *GraphQLObjectType) bool +type Abstract interface { + GetObjectType(value interface{}, info ResolveInfo) *Object + GetPossibleTypes() []*Object + IsPossibleType(ttype *Object) bool } -var _ GraphQLAbstractType = (*GraphQLInterfaceType)(nil) -var _ GraphQLAbstractType = (*GraphQLUnionType)(nil) +var _ Abstract = (*Interface)(nil) +var _ Abstract = (*Union)(nil) // These named types do not include modifiers like List or NonNull. -type GraphQLNamedType interface { +type Named interface { String() string } -var _ GraphQLNamedType = (*GraphQLScalarType)(nil) -var _ GraphQLNamedType = (*GraphQLObjectType)(nil) -var _ GraphQLNamedType = (*GraphQLInterfaceType)(nil) -var _ GraphQLNamedType = (*GraphQLUnionType)(nil) -var _ GraphQLNamedType = (*GraphQLEnumType)(nil) -var _ GraphQLNamedType = (*GraphQLInputObjectType)(nil) +var _ Named = (*Scalar)(nil) +var _ Named = (*Object)(nil) +var _ Named = (*Interface)(nil) +var _ Named = (*Union)(nil) +var _ Named = (*Enum)(nil) +var _ Named = (*InputObject)(nil) -func GetNamedType(ttype GraphQLType) GraphQLNamedType { +func GetNamedType(ttype Type) Named { unmodifiedType := ttype for { - if ttype, ok := unmodifiedType.(*GraphQLList); ok { + if ttype, ok := unmodifiedType.(*List); ok { unmodifiedType = ttype.OfType continue } - if ttype, ok := unmodifiedType.(*GraphQLNonNull); ok { + if ttype, ok := unmodifiedType.(*NonNull); ok { unmodifiedType = ttype.OfType continue } @@ -148,7 +148,7 @@ func GetNamedType(ttype GraphQLType) GraphQLNamedType { * * Example: * - * var OddType = new GraphQLScalarType({ + * var OddType = new Scalar({ * name: 'Odd', * serialize(value) { * return value % 2 === 1 ? value : null; @@ -156,17 +156,17 @@ func GetNamedType(ttype GraphQLType) GraphQLNamedType { * }); * */ -type GraphQLScalarType struct { +type Scalar struct { Name string `json:"name"` Description string `json:"description"` - scalarConfig GraphQLScalarTypeConfig + scalarConfig ScalarConfig err error } type SerializeFn func(value interface{}) interface{} type ParseValueFn func(value interface{}) interface{} type ParseLiteralFn func(valueAST ast.Value) interface{} -type GraphQLScalarTypeConfig struct { +type ScalarConfig struct { Name string `json:"name"` Description string `json:"description"` Serialize SerializeFn @@ -174,8 +174,8 @@ type GraphQLScalarTypeConfig struct { ParseLiteral ParseLiteralFn } -func NewGraphQLScalarType(config GraphQLScalarTypeConfig) *GraphQLScalarType { - st := &GraphQLScalarType{} +func NewScalar(config ScalarConfig) *Scalar { + st := &Scalar{} err := invariant(config.Name != "", "Type must be named.") if err != nil { st.err = err @@ -215,35 +215,35 @@ func NewGraphQLScalarType(config GraphQLScalarTypeConfig) *GraphQLScalarType { st.scalarConfig = config return st } -func (st *GraphQLScalarType) Serialize(value interface{}) interface{} { +func (st *Scalar) Serialize(value interface{}) interface{} { if st.scalarConfig.Serialize == nil { return value } return st.scalarConfig.Serialize(value) } -func (st *GraphQLScalarType) ParseValue(value interface{}) interface{} { +func (st *Scalar) ParseValue(value interface{}) interface{} { if st.scalarConfig.ParseValue == nil { return value } return st.scalarConfig.ParseValue(value) } -func (st *GraphQLScalarType) ParseLiteral(valueAST ast.Value) interface{} { +func (st *Scalar) ParseLiteral(valueAST ast.Value) interface{} { if st.scalarConfig.ParseLiteral == nil { return nil } return st.scalarConfig.ParseLiteral(valueAST) } -func (st *GraphQLScalarType) GetName() string { +func (st *Scalar) GetName() string { return st.Name } -func (st *GraphQLScalarType) GetDescription() string { +func (st *Scalar) GetDescription() string { return st.Description } -func (st *GraphQLScalarType) String() string { +func (st *Scalar) String() string { return st.Name } -func (st *GraphQLScalarType) GetError() error { +func (st *Scalar) GetError() error { return st.err } @@ -255,13 +255,13 @@ func (st *GraphQLScalarType) GetError() error { * * Example: * - * var AddressType = new GraphQLObjectType({ + * var AddressType = new Object({ * name: 'Address', * fields: { - * street: { type: GraphQLString }, - * number: { type: GraphQLInt }, + * street: { type: String }, + * number: { type: Int }, * formatted: { - * type: GraphQLString, + * type: String, * resolve(obj) { * return obj.number + ' ' + obj.street * } @@ -275,41 +275,41 @@ func (st *GraphQLScalarType) GetError() error { * * Example: * - * var PersonType = new GraphQLObjectType({ + * var PersonType = new Object({ * name: 'Person', * fields: () => ({ - * name: { type: GraphQLString }, + * name: { type: String }, * bestFriend: { type: PersonType }, * }) * }); * */ -type GraphQLObjectType struct { +type Object struct { Name string `json:"name"` Description string `json:"description"` IsTypeOf IsTypeOfFn - typeConfig GraphQLObjectTypeConfig - fields GraphQLFieldDefinitionMap - interfaces []*GraphQLInterfaceType + typeConfig ObjectConfig + fields FieldDefinitionMap + interfaces []*Interface // Interim alternative to throwing an error during schema definition at run-time err error } -type IsTypeOfFn func(value interface{}, info GraphQLResolveInfo) bool +type IsTypeOfFn func(value interface{}, info ResolveInfo) bool -type GraphQLInterfacesThunk func() []*GraphQLInterfaceType +type InterfacesThunk func() []*Interface -type GraphQLObjectTypeConfig struct { +type ObjectConfig struct { Name string `json:"description"` Interfaces interface{} `json:"interfaces"` - Fields GraphQLFieldConfigMap `json:"fields"` + Fields FieldConfigMap `json:"fields"` IsTypeOf IsTypeOfFn `json:"isTypeOf"` Description string `json:"description"` } -func NewGraphQLObjectType(config GraphQLObjectTypeConfig) *GraphQLObjectType { - objectType := &GraphQLObjectType{} +func NewObject(config ObjectConfig) *Object { + objectType := &Object{} err := invariant(config.Name != "", "Type must be named.") if err != nil { @@ -344,38 +344,38 @@ func NewGraphQLObjectType(config GraphQLObjectTypeConfig) *GraphQLObjectType { return objectType } -func (gt *GraphQLObjectType) AddFieldConfig(fieldName string, fieldConfig *GraphQLFieldConfig) { +func (gt *Object) AddFieldConfig(fieldName string, fieldConfig *FieldConfig) { if fieldName == "" || fieldConfig == nil { return } gt.typeConfig.Fields[fieldName] = fieldConfig } -func (gt *GraphQLObjectType) GetName() string { +func (gt *Object) GetName() string { return gt.Name } -func (gt *GraphQLObjectType) GetDescription() string { +func (gt *Object) GetDescription() string { return "" } -func (gt *GraphQLObjectType) String() string { +func (gt *Object) String() string { return gt.Name } -func (gt *GraphQLObjectType) GetFields() GraphQLFieldDefinitionMap { +func (gt *Object) GetFields() FieldDefinitionMap { fields, err := defineFieldMap(gt, gt.typeConfig.Fields) gt.err = err gt.fields = fields return gt.fields } -func (gt *GraphQLObjectType) GetInterfaces() []*GraphQLInterfaceType { - var configInterfaces []*GraphQLInterfaceType +func (gt *Object) GetInterfaces() []*Interface { + var configInterfaces []*Interface switch gt.typeConfig.Interfaces.(type) { - case GraphQLInterfacesThunk: - configInterfaces = gt.typeConfig.Interfaces.(GraphQLInterfacesThunk)() - case []*GraphQLInterfaceType: - configInterfaces = gt.typeConfig.Interfaces.([]*GraphQLInterfaceType) + case InterfacesThunk: + configInterfaces = gt.typeConfig.Interfaces.(InterfacesThunk)() + case []*Interface: + configInterfaces = gt.typeConfig.Interfaces.([]*Interface) case nil: default: - gt.err = errors.New(fmt.Sprintf("Unknown GraphQLObjectType.Interfaces type: %v", reflect.TypeOf(gt.typeConfig.Interfaces))) + gt.err = errors.New(fmt.Sprintf("Unknown Object.Interfaces type: %v", reflect.TypeOf(gt.typeConfig.Interfaces))) return nil } interfaces, err := defineInterfaces(gt, configInterfaces) @@ -383,12 +383,12 @@ func (gt *GraphQLObjectType) GetInterfaces() []*GraphQLInterfaceType { gt.interfaces = interfaces return gt.interfaces } -func (gt *GraphQLObjectType) GetError() error { +func (gt *Object) GetError() error { return gt.err } -func defineInterfaces(ttype *GraphQLObjectType, interfaces []*GraphQLInterfaceType) ([]*GraphQLInterfaceType, error) { - ifaces := []*GraphQLInterfaceType{} +func defineInterfaces(ttype *Object, interfaces []*Interface) ([]*Interface, error) { + ifaces := []*Interface{} if len(interfaces) == 0 { return ifaces, nil @@ -419,9 +419,9 @@ func defineInterfaces(ttype *GraphQLObjectType, interfaces []*GraphQLInterfaceTy return ifaces, nil } -func defineFieldMap(ttype GraphQLNamedType, fields GraphQLFieldConfigMap) (GraphQLFieldDefinitionMap, error) { +func defineFieldMap(ttype Named, fields FieldConfigMap) (FieldDefinitionMap, error) { - resultFieldMap := GraphQLFieldDefinitionMap{} + resultFieldMap := FieldDefinitionMap{} err := invariant( len(fields) > 0, @@ -449,7 +449,7 @@ func defineFieldMap(ttype GraphQLNamedType, fields GraphQLFieldConfigMap) (Graph if err != nil { return resultFieldMap, err } - fieldDef := &GraphQLFieldDefinition{ + fieldDef := &FieldDefinition{ Name: fieldName, Description: field.Description, Type: field.Type, @@ -457,7 +457,7 @@ func defineFieldMap(ttype GraphQLNamedType, fields GraphQLFieldConfigMap) (Graph DeprecationReason: field.DeprecationReason, } - fieldDef.Args = []*GraphQLArgument{} + fieldDef.Args = []*Argument{} for argName, arg := range field.Args { err := assertValidName(argName) if err != nil { @@ -477,7 +477,7 @@ func defineFieldMap(ttype GraphQLNamedType, fields GraphQLFieldConfigMap) (Graph if err != nil { return resultFieldMap, err } - fieldArg := &GraphQLArgument{ + fieldArg := &Argument{ Name: argName, Description: arg.Description, Type: arg.Type, @@ -494,79 +494,79 @@ func defineFieldMap(ttype GraphQLNamedType, fields GraphQLFieldConfigMap) (Graph type GQLFRParams struct { Source interface{} Args map[string]interface{} - Info GraphQLResolveInfo - Schema GraphQLSchema + Info ResolveInfo + Schema Schema } -// TODO: relook at GraphQLFieldResolveFn params -type GraphQLFieldResolveFn func(p GQLFRParams) interface{} +// TODO: relook at FieldResolveFn params +type FieldResolveFn func(p GQLFRParams) interface{} -type GraphQLResolveInfo struct { +type ResolveInfo struct { FieldName string FieldASTs []*ast.Field - ReturnType GraphQLOutputType - ParentType GraphQLCompositeType - Schema GraphQLSchema + ReturnType Output + ParentType Composite + Schema Schema Fragments map[string]ast.Definition RootValue interface{} Operation ast.Definition VariableValues map[string]interface{} } -type GraphQLFieldConfigMap map[string]*GraphQLFieldConfig +type FieldConfigMap map[string]*FieldConfig -type GraphQLFieldConfig struct { +type FieldConfig struct { Name string `json:"name"` // used by graphlql-relay - Type GraphQLOutputType `json:"type"` - Args GraphQLFieldConfigArgumentMap `json:"args"` - Resolve GraphQLFieldResolveFn + Type Output `json:"type"` + Args FieldConfigArgument `json:"args"` + Resolve FieldResolveFn DeprecationReason string `json:"deprecationReason"` Description string `json:"description"` } -type GraphQLFieldConfigArgumentMap map[string]*GraphQLArgumentConfig +type FieldConfigArgument map[string]*ArgumentConfig -type GraphQLArgumentConfig struct { - Type GraphQLInputType `json:"type"` +type ArgumentConfig struct { + Type Input `json:"type"` DefaultValue interface{} `json:"defaultValue"` Description string `json:"description"` } -type GraphQLFieldDefinitionMap map[string]*GraphQLFieldDefinition -type GraphQLFieldDefinition struct { +type FieldDefinitionMap map[string]*FieldDefinition +type FieldDefinition struct { Name string `json:"name"` Description string `json:"description"` - Type GraphQLOutputType `json:"type"` - Args []*GraphQLArgument `json:"args"` - Resolve GraphQLFieldResolveFn `json:"-"` + Type Output `json:"type"` + Args []*Argument `json:"args"` + Resolve FieldResolveFn `json:"-"` DeprecationReason string `json:"deprecationReason"` } -type GraphQLFieldArgument struct { +type FieldArgument struct { Name string `json:"name"` - Type GraphQLType `json:"type"` + Type Type `json:"type"` DefaultValue interface{} `json:"defaultValue"` Description string `json:"description"` } -type GraphQLArgument struct { +type Argument struct { Name string `json:"name"` - Type GraphQLInputType `json:"type"` + Type Input `json:"type"` DefaultValue interface{} `json:"defaultValue"` Description string `json:"description"` } -func (st *GraphQLArgument) GetName() string { +func (st *Argument) GetName() string { return st.Name } -func (st *GraphQLArgument) GetDescription() string { +func (st *Argument) GetDescription() string { return st.Description } -func (st *GraphQLArgument) String() string { +func (st *Argument) String() string { return st.Name } -func (st *GraphQLArgument) GetError() error { +func (st *Argument) GetError() error { return nil } @@ -580,36 +580,36 @@ func (st *GraphQLArgument) GetError() error { * * Example: * - * var EntityType = new GraphQLInterfaceType({ + * var EntityType = new Interface({ * name: 'Entity', * fields: { - * name: { type: GraphQLString } + * name: { type: String } * } * }); * */ -type GraphQLInterfaceType struct { +type Interface struct { Name string `json:"name"` Description string `json:"description"` ResolveType ResolveTypeFn - typeConfig GraphQLInterfaceTypeConfig - fields GraphQLFieldDefinitionMap - implementations []*GraphQLObjectType + typeConfig InterfaceConfig + fields FieldDefinitionMap + implementations []*Object possibleTypes map[string]bool err error } -type GraphQLInterfaceTypeConfig struct { +type InterfaceConfig struct { Name string `json:"name"` - Fields GraphQLFieldConfigMap `json:"fields"` + Fields FieldConfigMap `json:"fields"` ResolveType ResolveTypeFn Description string `json:"description"` } -type ResolveTypeFn func(value interface{}, info GraphQLResolveInfo) *GraphQLObjectType +type ResolveTypeFn func(value interface{}, info ResolveInfo) *Object -func NewGraphQLInterfaceType(config GraphQLInterfaceTypeConfig) *GraphQLInterfaceType { - it := &GraphQLInterfaceType{} +func NewInterface(config InterfaceConfig) *Interface { + it := &Interface{} err := invariant(config.Name != "", "Type must be named.") if err != nil { @@ -625,31 +625,31 @@ func NewGraphQLInterfaceType(config GraphQLInterfaceTypeConfig) *GraphQLInterfac it.Description = config.Description it.ResolveType = config.ResolveType it.typeConfig = config - it.implementations = []*GraphQLObjectType{} + it.implementations = []*Object{} return it } -func (it *GraphQLInterfaceType) AddFieldConfig(fieldName string, fieldConfig *GraphQLFieldConfig) { +func (it *Interface) AddFieldConfig(fieldName string, fieldConfig *FieldConfig) { if fieldName == "" || fieldConfig == nil { return } it.typeConfig.Fields[fieldName] = fieldConfig } -func (it *GraphQLInterfaceType) GetName() string { +func (it *Interface) GetName() string { return it.Name } -func (it *GraphQLInterfaceType) GetDescription() string { +func (it *Interface) GetDescription() string { return it.Description } -func (it *GraphQLInterfaceType) GetFields() (fields GraphQLFieldDefinitionMap) { +func (it *Interface) GetFields() (fields FieldDefinitionMap) { it.fields, it.err = defineFieldMap(it, it.typeConfig.Fields) return it.fields } -func (it *GraphQLInterfaceType) GetPossibleTypes() []*GraphQLObjectType { +func (it *Interface) GetPossibleTypes() []*Object { return it.implementations } -func (it *GraphQLInterfaceType) IsPossibleType(ttype *GraphQLObjectType) bool { +func (it *Interface) IsPossibleType(ttype *Object) bool { if ttype == nil { return false } @@ -668,20 +668,20 @@ func (it *GraphQLInterfaceType) IsPossibleType(ttype *GraphQLObjectType) bool { } return false } -func (it *GraphQLInterfaceType) GetObjectType(value interface{}, info GraphQLResolveInfo) *GraphQLObjectType { +func (it *Interface) GetObjectType(value interface{}, info ResolveInfo) *Object { if it.ResolveType != nil { return it.ResolveType(value, info) } return getTypeOf(value, info, it) } -func (it *GraphQLInterfaceType) String() string { +func (it *Interface) String() string { return it.Name } -func (it *GraphQLInterfaceType) GetError() error { +func (it *Interface) GetError() error { return it.err } -func getTypeOf(value interface{}, info GraphQLResolveInfo, abstractType GraphQLAbstractType) *GraphQLObjectType { +func getTypeOf(value interface{}, info ResolveInfo, abstractType Abstract) *Object { possibleTypes := abstractType.GetPossibleTypes() for _, possibleType := range possibleTypes { if possibleType.IsTypeOf == nil { @@ -703,7 +703,7 @@ func getTypeOf(value interface{}, info GraphQLResolveInfo, abstractType GraphQLA * * Example: * - * var PetType = new GraphQLUnionType({ + * var PetType = new Union({ * name: 'Pet', * types: [ DogType, CatType ], * resolveType(value) { @@ -717,26 +717,26 @@ func getTypeOf(value interface{}, info GraphQLResolveInfo, abstractType GraphQLA * }); * */ -type GraphQLUnionType struct { +type Union struct { Name string `json:"name"` Description string `json:"description"` ResolveType ResolveTypeFn - typeConfig GraphQLUnionTypeConfig - types []*GraphQLObjectType + typeConfig UnionConfig + types []*Object possibleTypes map[string]bool err error } -type GraphQLUnionTypeConfig struct { +type UnionConfig struct { Name string `json:"name"` - Types []*GraphQLObjectType `json:"types"` + Types []*Object `json:"types"` ResolveType ResolveTypeFn Description string `json:"description"` } -func NewGraphQLUnionType(config GraphQLUnionTypeConfig) *GraphQLUnionType { - objectType := &GraphQLUnionType{} +func NewUnion(config UnionConfig) *Union { + objectType := &Union{} err := invariant(config.Name != "", "Type must be named.") if err != nil { @@ -788,10 +788,10 @@ func NewGraphQLUnionType(config GraphQLUnionTypeConfig) *GraphQLUnionType { return objectType } -func (ut *GraphQLUnionType) GetPossibleTypes() []*GraphQLObjectType { +func (ut *Union) GetPossibleTypes() []*Object { return ut.types } -func (ut *GraphQLUnionType) IsPossibleType(ttype *GraphQLObjectType) bool { +func (ut *Union) IsPossibleType(ttype *Object) bool { if ttype == nil { return false @@ -812,22 +812,22 @@ func (ut *GraphQLUnionType) IsPossibleType(ttype *GraphQLObjectType) bool { } return false } -func (ut *GraphQLUnionType) GetObjectType(value interface{}, info GraphQLResolveInfo) *GraphQLObjectType { +func (ut *Union) GetObjectType(value interface{}, info ResolveInfo) *Object { if ut.ResolveType != nil { return ut.ResolveType(value, info) } return getTypeOf(value, info, ut) } -func (ut *GraphQLUnionType) String() string { +func (ut *Union) String() string { return ut.Name } -func (ut *GraphQLUnionType) GetName() string { +func (ut *Union) GetName() string { return ut.Name } -func (ut *GraphQLUnionType) GetDescription() string { +func (ut *Union) GetDescription() string { return ut.Description } -func (ut *GraphQLUnionType) GetError() error { +func (ut *Union) GetError() error { return ut.err } @@ -840,7 +840,7 @@ func (ut *GraphQLUnionType) GetError() error { * * Example: * - * var RGBType = new GraphQLEnumType({ + * var RGBType = new Enum({ * name: 'RGB', * values: { * RED: { value: 0 }, @@ -852,37 +852,37 @@ func (ut *GraphQLUnionType) GetError() error { * Note: If a value is not provided in a definition, the name of the enum value * will be used as it's internal value. */ -type GraphQLEnumType struct { +type Enum struct { Name string `json:"name"` Description string `json:"description"` - enumConfig GraphQLEnumTypeConfig - values []*GraphQLEnumValueDefinition - valuesLookup map[interface{}]*GraphQLEnumValueDefinition - nameLookup map[string]*GraphQLEnumValueDefinition + enumConfig EnumConfig + values []*EnumValueDefinition + valuesLookup map[interface{}]*EnumValueDefinition + nameLookup map[string]*EnumValueDefinition err error } -type GraphQLEnumValueConfigMap map[string]*GraphQLEnumValueConfig -type GraphQLEnumValueConfig struct { +type EnumValueConfigMap map[string]*EnumValueConfig +type EnumValueConfig struct { Value interface{} `json:"value"` DeprecationReason string `json:"deprecationReason"` Description string `json:"description"` } -type GraphQLEnumTypeConfig struct { +type EnumConfig struct { Name string `json:"name"` - Values GraphQLEnumValueConfigMap `json:"values"` + Values EnumValueConfigMap `json:"values"` Description string `json:"description"` } -type GraphQLEnumValueDefinition struct { +type EnumValueDefinition struct { Name string `json:"name"` Value interface{} `json:"value"` DeprecationReason string `json:"deprecationReason"` Description string `json:"description"` } -func NewGraphQLEnumType(config GraphQLEnumTypeConfig) *GraphQLEnumType { - gt := &GraphQLEnumType{} +func NewEnum(config EnumConfig) *Enum { + gt := &Enum{} gt.enumConfig = config err := assertValidName(config.Name) @@ -901,8 +901,8 @@ func NewGraphQLEnumType(config GraphQLEnumTypeConfig) *GraphQLEnumType { return gt } -func (gt *GraphQLEnumType) defineEnumValues(valueMap GraphQLEnumValueConfigMap) ([]*GraphQLEnumValueDefinition, error) { - values := []*GraphQLEnumValueDefinition{} +func (gt *Enum) defineEnumValues(valueMap EnumValueConfigMap) ([]*EnumValueDefinition, error) { + values := []*EnumValueDefinition{} err := invariant( len(valueMap) > 0, @@ -925,7 +925,7 @@ func (gt *GraphQLEnumType) defineEnumValues(valueMap GraphQLEnumValueConfigMap) if err != nil { return values, err } - value := &GraphQLEnumValueDefinition{ + value := &EnumValueDefinition{ Name: valueName, Value: valueConfig.Value, DeprecationReason: valueConfig.DeprecationReason, @@ -938,16 +938,16 @@ func (gt *GraphQLEnumType) defineEnumValues(valueMap GraphQLEnumValueConfigMap) } return values, nil } -func (gt *GraphQLEnumType) GetValues() []*GraphQLEnumValueDefinition { +func (gt *Enum) GetValues() []*EnumValueDefinition { return gt.values } -func (gt *GraphQLEnumType) Serialize(value interface{}) interface{} { +func (gt *Enum) Serialize(value interface{}) interface{} { if enumValue, ok := gt.getValueLookup()[value]; ok { return enumValue.Name } return nil } -func (gt *GraphQLEnumType) ParseValue(value interface{}) interface{} { +func (gt *Enum) ParseValue(value interface{}) interface{} { valueStr, ok := value.(string) if !ok { return nil @@ -957,7 +957,7 @@ func (gt *GraphQLEnumType) ParseValue(value interface{}) interface{} { } return nil } -func (gt *GraphQLEnumType) ParseLiteral(valueAST ast.Value) interface{} { +func (gt *Enum) ParseLiteral(valueAST ast.Value) interface{} { if valueAST, ok := valueAST.(*ast.EnumValue); ok { if enumValue, ok := gt.getNameLookup()[valueAST.Value]; ok { return enumValue.Value @@ -965,23 +965,23 @@ func (gt *GraphQLEnumType) ParseLiteral(valueAST ast.Value) interface{} { } return nil } -func (gt *GraphQLEnumType) GetName() string { +func (gt *Enum) GetName() string { return gt.Name } -func (gt *GraphQLEnumType) GetDescription() string { +func (gt *Enum) GetDescription() string { return "" } -func (gt *GraphQLEnumType) String() string { +func (gt *Enum) String() string { return gt.Name } -func (gt *GraphQLEnumType) GetError() error { +func (gt *Enum) GetError() error { return gt.err } -func (gt *GraphQLEnumType) getValueLookup() map[interface{}]*GraphQLEnumValueDefinition { +func (gt *Enum) getValueLookup() map[interface{}]*EnumValueDefinition { if len(gt.valuesLookup) > 0 { return gt.valuesLookup } - valuesLookup := map[interface{}]*GraphQLEnumValueDefinition{} + valuesLookup := map[interface{}]*EnumValueDefinition{} for _, value := range gt.GetValues() { valuesLookup[value.Value] = value } @@ -989,11 +989,11 @@ func (gt *GraphQLEnumType) getValueLookup() map[interface{}]*GraphQLEnumValueDef return gt.valuesLookup } -func (gt *GraphQLEnumType) getNameLookup() map[string]*GraphQLEnumValueDefinition { +func (gt *Enum) getNameLookup() map[string]*EnumValueDefinition { if len(gt.nameLookup) > 0 { return gt.nameLookup } - nameLookup := map[string]*GraphQLEnumValueDefinition{} + nameLookup := map[string]*EnumValueDefinition{} for _, value := range gt.GetValues() { nameLookup[value.Name] = value } @@ -1011,17 +1011,17 @@ func (gt *GraphQLEnumType) getNameLookup() map[string]*GraphQLEnumValueDefinitio * * Example: * - * var GeoPoint = new GraphQLInputObjectType({ + * var GeoPoint = new InputObject({ * name: 'GeoPoint', * fields: { - * lat: { type: new GraphQLNonNull(GraphQLFloat) }, - * lon: { type: new GraphQLNonNull(GraphQLFloat) }, - * alt: { type: GraphQLFloat, defaultValue: 0 }, + * lat: { type: new NonNull(Float) }, + * lon: { type: new NonNull(Float) }, + * alt: { type: Float, defaultValue: 0 }, * } * }); * */ -type GraphQLInputObjectType struct { +type InputObject struct { Name string `json:"name"` Description string `json:"description"` @@ -1031,13 +1031,13 @@ type GraphQLInputObjectType struct { err error } type InputObjectFieldConfig struct { - Type GraphQLInputType `json:"type"` + Type Input `json:"type"` DefaultValue interface{} `json:"defaultValue"` Description string `json:"description"` } type InputObjectField struct { Name string `json:"name"` - Type GraphQLInputType `json:"type"` + Type Input `json:"type"` DefaultValue interface{} `json:"defaultValue"` Description string `json:"description"` } @@ -1066,8 +1066,8 @@ type InputObjectConfig struct { } // TODO: rename InputObjectConfig to GraphQLInputObjecTypeConfig for consistency? -func NewGraphQLInputObjectType(config InputObjectConfig) *GraphQLInputObjectType { - gt := &GraphQLInputObjectType{} +func NewInputObject(config InputObjectConfig) *InputObject { + gt := &InputObject{} err := invariant(config.Name != "", "Type must be named.") if err != nil { gt.err = err @@ -1081,7 +1081,7 @@ func NewGraphQLInputObjectType(config InputObjectConfig) *GraphQLInputObjectType return gt } -func (gt *GraphQLInputObjectType) defineFieldMap() InputObjectFieldMap { +func (gt *InputObject) defineFieldMap() InputObjectFieldMap { var fieldMap InputObjectConfigFieldMap switch gt.typeConfig.Fields.(type) { case InputObjectConfigFieldMap: @@ -1125,19 +1125,19 @@ func (gt *GraphQLInputObjectType) defineFieldMap() InputObjectFieldMap { } return resultFieldMap } -func (gt *GraphQLInputObjectType) GetFields() InputObjectFieldMap { +func (gt *InputObject) GetFields() InputObjectFieldMap { return gt.fields } -func (gt *GraphQLInputObjectType) GetName() string { +func (gt *InputObject) GetName() string { return gt.Name } -func (gt *GraphQLInputObjectType) GetDescription() string { +func (gt *InputObject) GetDescription() string { return gt.Description } -func (gt *GraphQLInputObjectType) String() string { +func (gt *InputObject) String() string { return gt.Name } -func (gt *GraphQLInputObjectType) GetError() error { +func (gt *InputObject) GetError() error { return gt.err } @@ -1150,25 +1150,25 @@ func (gt *GraphQLInputObjectType) GetError() error { * * Example: * - * var PersonType = new GraphQLObjectType({ + * var PersonType = new Object({ * name: 'Person', * fields: () => ({ - * parents: { type: new GraphQLList(Person) }, - * children: { type: new GraphQLList(Person) }, + * parents: { type: new List(Person) }, + * children: { type: new List(Person) }, * }) * }) * */ -type GraphQLList struct { - OfType GraphQLType `json:"ofType"` +type List struct { + OfType Type `json:"ofType"` err error } -func NewGraphQLList(ofType GraphQLType) *GraphQLList { - gl := &GraphQLList{} +func NewList(ofType Type) *List { + gl := &List{} - err := invariant(ofType != nil, fmt.Sprintf(`Can only create List of a GraphQLType but got: %v.`, ofType)) + err := invariant(ofType != nil, fmt.Sprintf(`Can only create List of a Type but got: %v.`, ofType)) if err != nil { gl.err = err return gl @@ -1177,19 +1177,19 @@ func NewGraphQLList(ofType GraphQLType) *GraphQLList { gl.OfType = ofType return gl } -func (gl *GraphQLList) GetName() string { +func (gl *List) GetName() string { return fmt.Sprintf("%v", gl.OfType) } -func (gl *GraphQLList) GetDescription() string { +func (gl *List) GetDescription() string { return "" } -func (gl *GraphQLList) String() string { +func (gl *List) String() string { if gl.OfType != nil { return fmt.Sprintf("[%v]", gl.OfType) } return "" } -func (gl *GraphQLList) GetError() error { +func (gl *List) GetError() error { return gl.err } @@ -1204,27 +1204,27 @@ func (gl *GraphQLList) GetError() error { * * Example: * - * var RowType = new GraphQLObjectType({ + * var RowType = new Object({ * name: 'Row', * fields: () => ({ - * id: { type: new GraphQLNonNull(GraphQLString) }, + * id: { type: new NonNull(String) }, * }) * }) * * Note: the enforcement of non-nullability occurs within the executor. */ -type GraphQLNonNull struct { +type NonNull struct { Name string `json:"name"` // added to conform with introspection for NonNull.Name = nil - OfType GraphQLType `json:"ofType"` + OfType Type `json:"ofType"` err error } -func NewGraphQLNonNull(ofType GraphQLType) *GraphQLNonNull { - gl := &GraphQLNonNull{} +func NewNonNull(ofType Type) *NonNull { + gl := &NonNull{} - _, isOfTypeNonNull := ofType.(*GraphQLNonNull) - err := invariant(ofType != nil && !isOfTypeNonNull, fmt.Sprintf(`Can only create NonNull of a Nullable GraphQLType but got: %v.`, ofType)) + _, isOfTypeNonNull := ofType.(*NonNull) + err := invariant(ofType != nil && !isOfTypeNonNull, fmt.Sprintf(`Can only create NonNull of a Nullable Type but got: %v.`, ofType)) if err != nil { gl.err = err return gl @@ -1232,19 +1232,19 @@ func NewGraphQLNonNull(ofType GraphQLType) *GraphQLNonNull { gl.OfType = ofType return gl } -func (gl *GraphQLNonNull) GetName() string { +func (gl *NonNull) GetName() string { return fmt.Sprintf("%v!", gl.OfType) } -func (gl *GraphQLNonNull) GetDescription() string { +func (gl *NonNull) GetDescription() string { return "" } -func (gl *GraphQLNonNull) String() string { +func (gl *NonNull) String() string { if gl.OfType != nil { return gl.GetName() } return "" } -func (gl *GraphQLNonNull) GetError() error { +func (gl *NonNull) GetError() error { return gl.err } @@ -1260,7 +1260,7 @@ func assertValidName(name string) error { // TODO: there is another invariant() func in `executor` func invariant(condition bool, message string) error { if !condition { - return graphqlerrors.NewGraphQLFormattedError(message) + return graphqlerrors.NewFormattedError(message) } return nil } diff --git a/types/definition_test.go b/types/definition_test.go index 88bda225..32e1cfc4 100644 --- a/types/definition_test.go +++ b/types/definition_test.go @@ -9,122 +9,122 @@ import ( "github.com/chris-ramon/graphql/types" ) -var blogImage = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var blogImage = types.NewObject(types.ObjectConfig{ Name: "Image", - Fields: types.GraphQLFieldConfigMap{ - "url": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "url": &types.FieldConfig{ + Type: types.String, }, - "width": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, + "width": &types.FieldConfig{ + Type: types.Int, }, - "height": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, + "height": &types.FieldConfig{ + Type: types.Int, }, }, }) -var blogAuthor = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var blogAuthor = types.NewObject(types.ObjectConfig{ Name: "Author", - Fields: types.GraphQLFieldConfigMap{ - "id": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "id": &types.FieldConfig{ + Type: types.String, }, - "name": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "name": &types.FieldConfig{ + Type: types.String, }, - "pic": &types.GraphQLFieldConfig{ + "pic": &types.FieldConfig{ Type: blogImage, - Args: types.GraphQLFieldConfigArgumentMap{ - "width": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + Args: types.FieldConfigArgument{ + "width": &types.ArgumentConfig{ + Type: types.Int, }, - "height": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + "height": &types.ArgumentConfig{ + Type: types.Int, }, }, }, - "recentArticle": &types.GraphQLFieldConfig{}, + "recentArticle": &types.FieldConfig{}, }, }) -var blogArticle = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var blogArticle = types.NewObject(types.ObjectConfig{ Name: "Article", - Fields: types.GraphQLFieldConfigMap{ - "id": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "id": &types.FieldConfig{ + Type: types.String, }, - "isPublished": &types.GraphQLFieldConfig{ - Type: types.GraphQLBoolean, + "isPublished": &types.FieldConfig{ + Type: types.Boolean, }, - "author": &types.GraphQLFieldConfig{ + "author": &types.FieldConfig{ Type: blogAuthor, }, - "title": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "title": &types.FieldConfig{ + Type: types.String, }, - "body": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "body": &types.FieldConfig{ + Type: types.String, }, }, }) -var blogQuery = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var blogQuery = types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "article": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "article": &types.FieldConfig{ Type: blogArticle, - Args: types.GraphQLFieldConfigArgumentMap{ - "id": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Args: types.FieldConfigArgument{ + "id": &types.ArgumentConfig{ + Type: types.String, }, }, }, - "feed": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLList(blogArticle), + "feed": &types.FieldConfig{ + Type: types.NewList(blogArticle), }, }, }) -var blogMutation = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var blogMutation = types.NewObject(types.ObjectConfig{ Name: "Mutation", - Fields: types.GraphQLFieldConfigMap{ - "writeArticle": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "writeArticle": &types.FieldConfig{ Type: blogArticle, }, }, }) -var objectType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var objectType = types.NewObject(types.ObjectConfig{ Name: "Object", - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { return true }, }) -var interfaceType = types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ +var interfaceType = types.NewInterface(types.InterfaceConfig{ Name: "Interface", }) -var unionType = types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ +var unionType = types.NewUnion(types.UnionConfig{ Name: "Union", - Types: []*types.GraphQLObjectType{ + Types: []*types.Object{ objectType, }, }) -var enumType = types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ +var enumType = types.NewEnum(types.EnumConfig{ Name: "Enum", - Values: types.GraphQLEnumValueConfigMap{ - "foo": &types.GraphQLEnumValueConfig{}, + Values: types.EnumValueConfigMap{ + "foo": &types.EnumValueConfig{}, }, }) -var inputObjectType = types.NewGraphQLInputObjectType(types.InputObjectConfig{ +var inputObjectType = types.NewInputObject(types.InputObjectConfig{ Name: "InputObject", }) func init() { - blogAuthor.AddFieldConfig("recentArticle", &types.GraphQLFieldConfig{ + blogAuthor.AddFieldConfig("recentArticle", &types.FieldConfig{ Type: blogArticle, }) } func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { - blogSchema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + blogSchema, err := types.NewSchema(types.SchemaConfig{ Query: blogQuery, }) if err != nil { @@ -149,12 +149,12 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { if articleField.Name != "article" { t.Fatalf("articleField.Name expected to equal `article`, got: %v", articleField.Name) } - articleFieldTypeObject, ok := articleFieldType.(*types.GraphQLObjectType) + articleFieldTypeObject, ok := articleFieldType.(*types.Object) if !ok { - t.Fatalf("expected articleFieldType to be *types.GraphQLObjectType`, got: %v", articleField) + t.Fatalf("expected articleFieldType to be *types.Object`, got: %v", articleField) } - // TODO: expose a GraphQLObjectType.GetField(key string), instead of this ghetto way of accessing a field map? + // TODO: expose a Object.GetField(key string), instead of this ghetto way of accessing a field map? titleField := articleFieldTypeObject.GetFields()["title"] if titleField == nil { t.Fatalf("titleField is nil") @@ -162,8 +162,8 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { if titleField.Name != "title" { t.Fatalf("titleField.Name expected to equal title, got: %v", titleField.Name) } - if titleField.Type != types.GraphQLString { - t.Fatalf("titleField.Type expected to equal types.GraphQLString, got: %v", titleField.Type) + if titleField.Type != types.String { + t.Fatalf("titleField.Type expected to equal types.String, got: %v", titleField.Type) } if titleField.Type.GetName() != "String" { t.Fatalf("titleField.Type.GetName() expected to equal `String`, got: %v", titleField.Type.GetName()) @@ -173,9 +173,9 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { if authorField == nil { t.Fatalf("authorField is nil") } - authorFieldObject, ok := authorField.Type.(*types.GraphQLObjectType) + authorFieldObject, ok := authorField.Type.(*types.Object) if !ok { - t.Fatalf("expected authorField.Type to be *types.GraphQLObjectType`, got: %v", authorField) + t.Fatalf("expected authorField.Type to be *types.Object`, got: %v", authorField) } recentArticleField := authorFieldObject.GetFields()["recentArticle"] @@ -187,9 +187,9 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { } feedField := blogQuery.GetFields()["feed"] - feedFieldList, ok := feedField.Type.(*types.GraphQLList) + feedFieldList, ok := feedField.Type.(*types.List) if !ok { - t.Fatalf("expected feedFieldList to be *types.GraphQLList`, got: %v", authorField) + t.Fatalf("expected feedFieldList to be *types.List`, got: %v", authorField) } if feedFieldList.OfType != blogArticle { t.Fatalf("feedFieldList.OfType expected to equal blogArticle, got: %v", feedFieldList.OfType) @@ -199,7 +199,7 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { } } func TestTypeSystem_DefinitionExample_DefinesAMutationScheme(t *testing.T) { - blogSchema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + blogSchema, err := types.NewSchema(types.SchemaConfig{ Query: blogQuery, Mutation: blogMutation, }) @@ -228,15 +228,15 @@ func TestTypeSystem_DefinitionExample_DefinesAMutationScheme(t *testing.T) { } func TestTypeSystem_DefinitionExample_IncludesNestedInputObjectsInTheMap(t *testing.T) { - nestedInputObject := types.NewGraphQLInputObjectType(types.InputObjectConfig{ + nestedInputObject := types.NewInputObject(types.InputObjectConfig{ Name: "NestedInputObject", Fields: types.InputObjectConfigFieldMap{ "value": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, }, }, }) - someInputObject := types.NewGraphQLInputObjectType(types.InputObjectConfig{ + someInputObject := types.NewInputObject(types.InputObjectConfig{ Name: "SomeInputObject", Fields: types.InputObjectConfigFieldMap{ "nested": &types.InputObjectFieldConfig{ @@ -244,20 +244,20 @@ func TestTypeSystem_DefinitionExample_IncludesNestedInputObjectsInTheMap(t *test }, }, }) - someMutation := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + someMutation := types.NewObject(types.ObjectConfig{ Name: "SomeMutation", - Fields: types.GraphQLFieldConfigMap{ - "mutateSomething": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "mutateSomething": &types.FieldConfig{ Type: blogArticle, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ Type: someInputObject, }, }, }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: blogQuery, Mutation: someMutation, }) @@ -271,32 +271,32 @@ func TestTypeSystem_DefinitionExample_IncludesNestedInputObjectsInTheMap(t *test func TestTypeSystem_DefinitionExample_IncludesInterfacesSubTypesInTheTypeMap(t *testing.T) { - someInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + someInterface := types.NewInterface(types.InterfaceConfig{ Name: "SomeInterface", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.Int, }, }, }) - someSubType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + someSubType := types.NewObject(types.ObjectConfig{ Name: "SomeSubtype", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.Int, }, }, - Interfaces: []*types.GraphQLInterfaceType{someInterface}, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + Interfaces: []*types.Interface{someInterface}, + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { return true }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "iface": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "iface": &types.FieldConfig{ Type: someInterface, }, }, @@ -312,34 +312,34 @@ func TestTypeSystem_DefinitionExample_IncludesInterfacesSubTypesInTheTypeMap(t * func TestTypeSystem_DefinitionExample_IncludesInterfacesThunkSubtypesInTheTypeMap(t *testing.T) { - someInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + someInterface := types.NewInterface(types.InterfaceConfig{ Name: "SomeInterface", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.Int, }, }, }) - someSubType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + someSubType := types.NewObject(types.ObjectConfig{ Name: "SomeSubtype", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.Int, }, }, - Interfaces: (types.GraphQLInterfacesThunk)(func() []*types.GraphQLInterfaceType { - return []*types.GraphQLInterfaceType{someInterface} + Interfaces: (types.InterfacesThunk)(func() []*types.Interface { + return []*types.Interface{someInterface} }), - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { return true }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "iface": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "iface": &types.FieldConfig{ Type: someInterface, }, }, @@ -356,21 +356,21 @@ func TestTypeSystem_DefinitionExample_IncludesInterfacesThunkSubtypesInTheTypeMa func TestTypeSystem_DefinitionExample_StringifiesSimpleTypes(t *testing.T) { type Test struct { - ttype types.GraphQLType + ttype types.Type expected string } tests := []Test{ - Test{types.GraphQLInt, "Int"}, + Test{types.Int, "Int"}, Test{blogArticle, "Article"}, Test{interfaceType, "Interface"}, Test{unionType, "Union"}, Test{enumType, "Enum"}, Test{inputObjectType, "InputObject"}, - Test{types.NewGraphQLNonNull(types.GraphQLInt), "Int!"}, - Test{types.NewGraphQLList(types.GraphQLInt), "[Int]"}, - Test{types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLInt)), "[Int]!"}, - Test{types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLInt)), "[Int!]"}, - Test{types.NewGraphQLList(types.NewGraphQLList(types.GraphQLInt)), "[[Int]]"}, + Test{types.NewNonNull(types.Int), "Int!"}, + Test{types.NewList(types.Int), "[Int]"}, + Test{types.NewNonNull(types.NewList(types.Int)), "[Int]!"}, + Test{types.NewList(types.NewNonNull(types.Int)), "[Int!]"}, + Test{types.NewList(types.NewList(types.Int)), "[[Int]]"}, } for _, test := range tests { ttypeStr := fmt.Sprintf("%v", test.ttype) @@ -382,11 +382,11 @@ func TestTypeSystem_DefinitionExample_StringifiesSimpleTypes(t *testing.T) { func TestTypeSystem_DefinitionExample_IdentifiesInputTypes(t *testing.T) { type Test struct { - ttype types.GraphQLType + ttype types.Type expected bool } tests := []Test{ - Test{types.GraphQLInt, true}, + Test{types.Int, true}, Test{objectType, false}, Test{interfaceType, false}, Test{unionType, false}, @@ -398,10 +398,10 @@ func TestTypeSystem_DefinitionExample_IdentifiesInputTypes(t *testing.T) { if types.IsInputType(test.ttype) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } - if types.IsInputType(types.NewGraphQLList(test.ttype)) != test.expected { + if types.IsInputType(types.NewList(test.ttype)) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } - if types.IsInputType(types.NewGraphQLNonNull(test.ttype)) != test.expected { + if types.IsInputType(types.NewNonNull(test.ttype)) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } } @@ -409,11 +409,11 @@ func TestTypeSystem_DefinitionExample_IdentifiesInputTypes(t *testing.T) { func TestTypeSystem_DefinitionExample_IdentifiesOutputTypes(t *testing.T) { type Test struct { - ttype types.GraphQLType + ttype types.Type expected bool } tests := []Test{ - Test{types.GraphQLInt, true}, + Test{types.Int, true}, Test{objectType, true}, Test{interfaceType, true}, Test{unionType, true}, @@ -425,33 +425,33 @@ func TestTypeSystem_DefinitionExample_IdentifiesOutputTypes(t *testing.T) { if types.IsOutputType(test.ttype) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } - if types.IsOutputType(types.NewGraphQLList(test.ttype)) != test.expected { + if types.IsOutputType(types.NewList(test.ttype)) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } - if types.IsOutputType(types.NewGraphQLNonNull(test.ttype)) != test.expected { + if types.IsOutputType(types.NewNonNull(test.ttype)) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } } } func TestTypeSystem_DefinitionExample_ProhibitsNestingNonNullInsideNonNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(types.NewGraphQLNonNull(types.GraphQLInt)) - expected := `Can only create NonNull of a Nullable GraphQLType but got: Int!.` + ttype := types.NewNonNull(types.NewNonNull(types.Int)) + expected := `Can only create NonNull of a Nullable Type but got: Int!.` if ttype.GetError().Error() != expected { t.Fatalf(`expected %v , got: %v`, expected, ttype.GetError()) } } func TestTypeSystem_DefinitionExample_ProhibitsNilInNonNull(t *testing.T) { - ttype := types.NewGraphQLNonNull(nil) - expected := `Can only create NonNull of a Nullable GraphQLType but got: .` + ttype := types.NewNonNull(nil) + expected := `Can only create NonNull of a Nullable Type but got: .` if ttype.GetError().Error() != expected { t.Fatalf(`expected %v , got: %v`, expected, ttype.GetError()) } } func TestTypeSystem_DefinitionExample_ProhibitsNilTypeInUnions(t *testing.T) { - ttype := types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + ttype := types.NewUnion(types.UnionConfig{ Name: "BadUnion", - Types: []*types.GraphQLObjectType{nil}, + Types: []*types.Object{nil}, }) expected := `BadUnion may only contain Object types, it cannot contain: .` if ttype.GetError().Error() != expected { @@ -459,24 +459,24 @@ func TestTypeSystem_DefinitionExample_ProhibitsNilTypeInUnions(t *testing.T) { } } func TestTypeSystem_DefinitionExample_DoesNotMutatePassedFieldDefinitions(t *testing.T) { - fields := types.GraphQLFieldConfigMap{ - "field1": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + fields := types.FieldConfigMap{ + "field1": &types.FieldConfig{ + Type: types.String, }, - "field2": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "id": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + "field2": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "id": &types.ArgumentConfig{ + Type: types.String, }, }, }, } - testObject1 := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + testObject1 := types.NewObject(types.ObjectConfig{ Name: "Test1", Fields: fields, }) - testObject2 := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + testObject2 := types.NewObject(types.ObjectConfig{ Name: "Test2", Fields: fields, }) @@ -484,15 +484,15 @@ func TestTypeSystem_DefinitionExample_DoesNotMutatePassedFieldDefinitions(t *tes t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(testObject1.GetFields(), testObject2.GetFields())) } - expectedFields := types.GraphQLFieldConfigMap{ - "field1": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + expectedFields := types.FieldConfigMap{ + "field1": &types.FieldConfig{ + Type: types.String, }, - "field2": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "id": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + "field2": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "id": &types.ArgumentConfig{ + Type: types.String, }, }, }, @@ -503,25 +503,25 @@ func TestTypeSystem_DefinitionExample_DoesNotMutatePassedFieldDefinitions(t *tes inputFields := types.InputObjectConfigFieldMap{ "field1": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, }, "field2": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, }, } expectedInputFields := types.InputObjectConfigFieldMap{ "field1": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, }, "field2": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, }, } - testInputObject1 := types.NewGraphQLInputObjectType(types.InputObjectConfig{ + testInputObject1 := types.NewInputObject(types.InputObjectConfig{ Name: "Test1", Fields: inputFields, }) - testInputObject2 := types.NewGraphQLInputObjectType(types.InputObjectConfig{ + testInputObject2 := types.NewInputObject(types.InputObjectConfig{ Name: "Test2", Fields: inputFields, }) diff --git a/types/directives.go b/types/directives.go index 2d93f5e4..93cdb820 100644 --- a/types/directives.go +++ b/types/directives.go @@ -1,9 +1,9 @@ package types -type GraphQLDirective struct { +type Directive struct { Name string `json:"name"` Description string `json:"description"` - Args []*GraphQLArgument `json:"args"` + Args []*Argument `json:"args"` OnOperation bool `json:"onOperation"` OnFragment bool `json:"onFragment"` OnField bool `json:"onField"` @@ -13,11 +13,11 @@ type GraphQLDirective struct { * Directives are used by the GraphQL runtime as a way of modifying execution * behavior. Type system creators will usually not create these directly. */ -func NewGraphQLDirective(config *GraphQLDirective) *GraphQLDirective { +func NewDirective(config *Directive) *Directive { if config == nil { - config = &GraphQLDirective{} + config = &Directive{} } - return &GraphQLDirective{ + return &Directive{ Name: config.Name, Description: config.Description, Args: config.Args, @@ -30,14 +30,14 @@ func NewGraphQLDirective(config *GraphQLDirective) *GraphQLDirective { /** * Used to conditionally include fields or fragments */ -var GraphQLIncludeDirective *GraphQLDirective = NewGraphQLDirective(&GraphQLDirective{ +var IncludeDirective *Directive = NewDirective(&Directive{ Name: "include", Description: "Directs the executor to include this field or fragment only when " + "the `if` argument is true.", - Args: []*GraphQLArgument{ - &GraphQLArgument{ + Args: []*Argument{ + &Argument{ Name: "if", - Type: NewGraphQLNonNull(GraphQLBoolean), + Type: NewNonNull(Boolean), Description: "Included when true.", }, }, @@ -49,14 +49,14 @@ var GraphQLIncludeDirective *GraphQLDirective = NewGraphQLDirective(&GraphQLDire /** * Used to conditionally skip (exclude) fields or fragments */ -var GraphQLSkipDirective *GraphQLDirective = NewGraphQLDirective(&GraphQLDirective{ +var SkipDirective *Directive = NewDirective(&Directive{ Name: "skip", Description: "Directs the executor to skip this field or fragment when the `if` " + "argument is true.", - Args: []*GraphQLArgument{ - &GraphQLArgument{ + Args: []*Argument{ + &Argument{ Name: "if", - Type: NewGraphQLNonNull(GraphQLBoolean), + Type: NewNonNull(Boolean), Description: "Skipped when true.", }, }, diff --git a/types/enum_type_test.go b/types/enum_type_test.go index 4e367ec0..742f8056 100644 --- a/types/enum_type_test.go +++ b/types/enum_type_test.go @@ -9,34 +9,34 @@ import ( "testing" ) -var enumTypeTestColorType = types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ +var enumTypeTestColorType = types.NewEnum(types.EnumConfig{ Name: "Color", - Values: types.GraphQLEnumValueConfigMap{ - "RED": &types.GraphQLEnumValueConfig{ + Values: types.EnumValueConfigMap{ + "RED": &types.EnumValueConfig{ Value: 0, }, - "GREEN": &types.GraphQLEnumValueConfig{ + "GREEN": &types.EnumValueConfig{ Value: 1, }, - "BLUE": &types.GraphQLEnumValueConfig{ + "BLUE": &types.EnumValueConfig{ Value: 2, }, }, }) -var enumTypeTestQueryType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var enumTypeTestQueryType = types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "colorEnum": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "colorEnum": &types.FieldConfig{ Type: enumTypeTestColorType, - Args: types.GraphQLFieldConfigArgumentMap{ - "fromEnum": &types.GraphQLArgumentConfig{ + Args: types.FieldConfigArgument{ + "fromEnum": &types.ArgumentConfig{ Type: enumTypeTestColorType, }, - "fromInt": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + "fromInt": &types.ArgumentConfig{ + Type: types.Int, }, - "fromString": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + "fromString": &types.ArgumentConfig{ + Type: types.String, }, }, Resolve: func(p types.GQLFRParams) interface{} { @@ -52,14 +52,14 @@ var enumTypeTestQueryType = types.NewGraphQLObjectType(types.GraphQLObjectTypeCo return nil }, }, - "colorInt": &types.GraphQLFieldConfig{ - Type: types.GraphQLInt, - Args: types.GraphQLFieldConfigArgumentMap{ - "fromEnum": &types.GraphQLArgumentConfig{ + "colorInt": &types.FieldConfig{ + Type: types.Int, + Args: types.FieldConfigArgument{ + "fromEnum": &types.ArgumentConfig{ Type: enumTypeTestColorType, }, - "fromInt": &types.GraphQLArgumentConfig{ - Type: types.GraphQLInt, + "fromInt": &types.ArgumentConfig{ + Type: types.Int, }, }, Resolve: func(p types.GQLFRParams) interface{} { @@ -74,13 +74,13 @@ var enumTypeTestQueryType = types.NewGraphQLObjectType(types.GraphQLObjectTypeCo }, }, }) -var enumTypeTestMutationType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var enumTypeTestMutationType = types.NewObject(types.ObjectConfig{ Name: "Mutation", - Fields: types.GraphQLFieldConfigMap{ - "favoriteEnum": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "favoriteEnum": &types.FieldConfig{ Type: enumTypeTestColorType, - Args: types.GraphQLFieldConfigArgumentMap{ - "color": &types.GraphQLArgumentConfig{ + Args: types.FieldConfigArgument{ + "color": &types.ArgumentConfig{ Type: enumTypeTestColorType, }, }, @@ -93,20 +93,20 @@ var enumTypeTestMutationType = types.NewGraphQLObjectType(types.GraphQLObjectTyp }, }, }) -var enumTypeTestSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{ +var enumTypeTestSchema, _ = types.NewSchema(types.SchemaConfig{ Query: enumTypeTestQueryType, Mutation: enumTypeTestMutationType, }) -func executeEnumTypeTest(t *testing.T, query string) *types.GraphQLResult { - result := g(t, graphql.GraphqlParams{ +func executeEnumTypeTest(t *testing.T, query string) *types.Result { + result := g(t, graphql.Params{ Schema: enumTypeTestSchema, RequestString: query, }) return result } -func executeEnumTypeTestWithParams(t *testing.T, query string, params map[string]interface{}) *types.GraphQLResult { - result := g(t, graphql.GraphqlParams{ +func executeEnumTypeTestWithParams(t *testing.T, query string, params map[string]interface{}) *types.Result { + result := g(t, graphql.Params{ Schema: enumTypeTestSchema, RequestString: query, VariableValues: params, @@ -115,7 +115,7 @@ func executeEnumTypeTestWithParams(t *testing.T, query string, params map[string } func TestTypeSystem_EnumValues_AcceptsEnumLiteralsAsInput(t *testing.T) { query := "{ colorInt(fromEnum: GREEN) }" - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "colorInt": 1, }, @@ -128,7 +128,7 @@ func TestTypeSystem_EnumValues_AcceptsEnumLiteralsAsInput(t *testing.T) { func TestTypeSystem_EnumValues_EnumMayBeOutputType(t *testing.T) { query := "{ colorEnum(fromInt: 1) }" - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "colorEnum": "GREEN", }, @@ -140,7 +140,7 @@ func TestTypeSystem_EnumValues_EnumMayBeOutputType(t *testing.T) { } func TestTypeSystem_EnumValues_EnumMayBeBothInputAndOutputType(t *testing.T) { query := "{ colorEnum(fromEnum: GREEN) }" - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "colorEnum": "GREEN", }, @@ -152,10 +152,10 @@ func TestTypeSystem_EnumValues_EnumMayBeBothInputAndOutputType(t *testing.T) { } func TestTypeSystem_EnumValues_DoesNotAcceptStringLiterals(t *testing.T) { query := `{ colorEnum(fromEnum: "GREEN") }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Argument "fromEnum" expected type "Color" but got: "GREEN".`, }, }, @@ -168,7 +168,7 @@ func TestTypeSystem_EnumValues_DoesNotAcceptStringLiterals(t *testing.T) { } func TestTypeSystem_EnumValues_DoesNotAcceptIncorrectInternalValue(t *testing.T) { query := `{ colorEnum(fromString: "GREEN") }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "colorEnum": nil, }, @@ -180,10 +180,10 @@ func TestTypeSystem_EnumValues_DoesNotAcceptIncorrectInternalValue(t *testing.T) } func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueInPlaceOfEnumLiteral(t *testing.T) { query := `{ colorEnum(fromEnum: 1) }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Argument "fromEnum" expected type "Color" but got: 1.`, }, }, @@ -197,10 +197,10 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueInPlaceOfEnumLiteral(t func TestTypeSystem_EnumValues_DoesNotAcceptEnumLiteralInPlaceOfInt(t *testing.T) { query := `{ colorEnum(fromInt: GREEN) }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Argument "fromInt" expected type "Int" but got: GREEN.`, }, }, @@ -217,7 +217,7 @@ func TestTypeSystem_EnumValues_AcceptsJSONStringAsEnumVariable(t *testing.T) { params := map[string]interface{}{ "color": "BLUE", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "colorEnum": "BLUE", }, @@ -233,7 +233,7 @@ func TestTypeSystem_EnumValues_AcceptsEnumLiteralsAsInputArgumentsToMutations(t params := map[string]interface{}{ "color": "GREEN", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "favoriteEnum": "GREEN", }, @@ -248,10 +248,10 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueAsEnumVariable(t *testi params := map[string]interface{}{ "color": 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$color" expected value of type "Color!" but got: 2.`, }, }, @@ -267,10 +267,10 @@ func TestTypeSystem_EnumValues_DoesNotAcceptStringVariablesAsEnumInput(t *testin params := map[string]interface{}{ "color": "BLUE", } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$color" of type "String!" used in position expecting type "Color".`, }, }, @@ -286,10 +286,10 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueVariableAsEnumInput(t * params := map[string]interface{}{ "color": 2, } - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: nil, - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Variable "$color" of type "Int!" used in position expecting type "Color".`, }, }, @@ -305,7 +305,7 @@ func TestTypeSystem_EnumValues_EnumValueMayHaveAnInternalValueOfZero(t *testing. colorEnum(fromEnum: RED) colorInt(fromEnum: RED) }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "colorEnum": "RED", "colorInt": 0, @@ -321,7 +321,7 @@ func TestTypeSystem_EnumValues_EnumValueMayBeNullable(t *testing.T) { colorEnum colorInt }` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "colorEnum": nil, "colorInt": nil, diff --git a/types/introspection.go b/types/introspection.go index fd6e61e9..4ff88d4b 100644 --- a/types/introspection.go +++ b/types/introspection.go @@ -19,60 +19,60 @@ const ( TypeKindNonNull = "NON_NULL" ) -var __Directive *GraphQLObjectType -var __Schema *GraphQLObjectType -var __Type *GraphQLObjectType -var __Field *GraphQLObjectType -var __InputValue *GraphQLObjectType -var __EnumValue *GraphQLObjectType +var __Directive *Object +var __Schema *Object +var __Type *Object +var __Field *Object +var __InputValue *Object +var __EnumValue *Object -var __TypeKind *GraphQLEnumType +var __TypeKind *Enum -var SchemaMetaFieldDef *GraphQLFieldDefinition -var TypeMetaFieldDef *GraphQLFieldDefinition -var TypeNameMetaFieldDef *GraphQLFieldDefinition +var SchemaMetaFieldDef *FieldDefinition +var TypeMetaFieldDef *FieldDefinition +var TypeNameMetaFieldDef *FieldDefinition func init() { - __TypeKind = NewGraphQLEnumType(GraphQLEnumTypeConfig{ + __TypeKind = NewEnum(EnumConfig{ Name: "__TypeKind", Description: "An enum describing what kind of type a given __Type is", - Values: GraphQLEnumValueConfigMap{ - "SCALAR": &GraphQLEnumValueConfig{ + Values: EnumValueConfigMap{ + "SCALAR": &EnumValueConfig{ Value: TypeKindScalar, Description: "Indicates this type is a scalar.", }, - "OBJECT": &GraphQLEnumValueConfig{ + "OBJECT": &EnumValueConfig{ Value: TypeKindObject, Description: "Indicates this type is an object. " + "`fields` and `interfaces` are valid fields.", }, - "INTERFACE": &GraphQLEnumValueConfig{ + "INTERFACE": &EnumValueConfig{ Value: TypeKindInterface, Description: "Indicates this type is an interface. " + "`fields` and `possibleTypes` are valid fields.", }, - "UNION": &GraphQLEnumValueConfig{ + "UNION": &EnumValueConfig{ Value: TypeKindUnion, Description: "Indicates this type is a union. " + "`possibleTypes` is a valid field.", }, - "ENUM": &GraphQLEnumValueConfig{ + "ENUM": &EnumValueConfig{ Value: TypeKindEnum, Description: "Indicates this type is an enum. " + "`enumValues` is a valid field.", }, - "INPUT_OBJECT": &GraphQLEnumValueConfig{ + "INPUT_OBJECT": &EnumValueConfig{ Value: TypeKindInputObject, Description: "Indicates this type is an input object. " + "`inputFields` is a valid field.", }, - "LIST": &GraphQLEnumValueConfig{ + "LIST": &EnumValueConfig{ Value: TypeKindList, Description: "Indicates this type is a list. " + "`ofType` is a valid field.", }, - "NON_NULL": &GraphQLEnumValueConfig{ + "NON_NULL": &EnumValueConfig{ Value: TypeKindNonNull, Description: "Indicates this type is a non-null. " + "`ofType` is a valid field.", @@ -81,64 +81,64 @@ func init() { }) // Note: some fields (for e.g "fields", "interfaces") are defined later due to cyclic reference - __Type = NewGraphQLObjectType(GraphQLObjectTypeConfig{ + __Type = NewObject(ObjectConfig{ Name: "__Type", - Fields: GraphQLFieldConfigMap{ - "kind": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(__TypeKind), + Fields: FieldConfigMap{ + "kind": &FieldConfig{ + Type: NewNonNull(__TypeKind), Resolve: func(p GQLFRParams) interface{} { switch p.Source.(type) { - case *GraphQLScalarType: + case *Scalar: return TypeKindScalar - case *GraphQLObjectType: + case *Object: return TypeKindObject - case *GraphQLInterfaceType: + case *Interface: return TypeKindInterface - case *GraphQLUnionType: + case *Union: return TypeKindUnion - case *GraphQLEnumType: + case *Enum: return TypeKindEnum - case *GraphQLInputObjectType: + case *InputObject: return TypeKindInputObject - case *GraphQLList: + case *List: return TypeKindList - case *GraphQLNonNull: + case *NonNull: return TypeKindNonNull } panic(fmt.Sprintf("Unknown kind of type: %v", p.Source)) }, }, - "name": &GraphQLFieldConfig{ - Type: GraphQLString, + "name": &FieldConfig{ + Type: String, }, - "description": &GraphQLFieldConfig{ - Type: GraphQLString, + "description": &FieldConfig{ + Type: String, }, - "fields": &GraphQLFieldConfig{}, - "interfaces": &GraphQLFieldConfig{}, - "possibleTypes": &GraphQLFieldConfig{}, - "enumValues": &GraphQLFieldConfig{}, - "inputFields": &GraphQLFieldConfig{}, - "ofType": &GraphQLFieldConfig{}, + "fields": &FieldConfig{}, + "interfaces": &FieldConfig{}, + "possibleTypes": &FieldConfig{}, + "enumValues": &FieldConfig{}, + "inputFields": &FieldConfig{}, + "ofType": &FieldConfig{}, }, }) - __InputValue = NewGraphQLObjectType(GraphQLObjectTypeConfig{ + __InputValue = NewObject(ObjectConfig{ Name: "__InputValue", - Fields: GraphQLFieldConfigMap{ - "name": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(GraphQLString), + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: NewNonNull(String), }, - "description": &GraphQLFieldConfig{ - Type: GraphQLString, + "description": &FieldConfig{ + Type: String, }, - "type": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(__Type), + "type": &FieldConfig{ + Type: NewNonNull(__Type), }, - "defaultValue": &GraphQLFieldConfig{ - Type: GraphQLString, + "defaultValue": &FieldConfig{ + Type: String, Resolve: func(p GQLFRParams) interface{} { - if inputVal, ok := p.Source.(*GraphQLArgument); ok { + if inputVal, ok := p.Source.(*Argument); ok { if inputVal.DefaultValue == nil { return nil } @@ -158,107 +158,107 @@ func init() { }, }) - __Field = NewGraphQLObjectType(GraphQLObjectTypeConfig{ + __Field = NewObject(ObjectConfig{ Name: "__Field", - Fields: GraphQLFieldConfigMap{ - "name": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(GraphQLString), + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: NewNonNull(String), }, - "description": &GraphQLFieldConfig{ - Type: GraphQLString, + "description": &FieldConfig{ + Type: String, }, - "args": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(NewGraphQLList(NewGraphQLNonNull(__InputValue))), + "args": &FieldConfig{ + Type: NewNonNull(NewList(NewNonNull(__InputValue))), Resolve: func(p GQLFRParams) interface{} { - if field, ok := p.Source.(*GraphQLFieldDefinition); ok { + if field, ok := p.Source.(*FieldDefinition); ok { return field.Args } return []interface{}{} }, }, - "type": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(__Type), + "type": &FieldConfig{ + Type: NewNonNull(__Type), }, - "isDeprecated": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(GraphQLBoolean), + "isDeprecated": &FieldConfig{ + Type: NewNonNull(Boolean), Resolve: func(p GQLFRParams) interface{} { - if field, ok := p.Source.(*GraphQLFieldDefinition); ok { + if field, ok := p.Source.(*FieldDefinition); ok { return (field.DeprecationReason != "") } return false }, }, - "deprecationReason": &GraphQLFieldConfig{ - Type: GraphQLString, + "deprecationReason": &FieldConfig{ + Type: String, }, }, }) - __Directive = NewGraphQLObjectType(GraphQLObjectTypeConfig{ + __Directive = NewObject(ObjectConfig{ Name: "__Directive", - Fields: GraphQLFieldConfigMap{ - "name": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(GraphQLString), + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: NewNonNull(String), }, - "description": &GraphQLFieldConfig{ - Type: GraphQLString, + "description": &FieldConfig{ + Type: String, }, - "args": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(NewGraphQLList( - NewGraphQLNonNull(__InputValue), + "args": &FieldConfig{ + Type: NewNonNull(NewList( + NewNonNull(__InputValue), )), }, - "onOperation": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(GraphQLBoolean), + "onOperation": &FieldConfig{ + Type: NewNonNull(Boolean), }, - "onFragment": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(GraphQLBoolean), + "onFragment": &FieldConfig{ + Type: NewNonNull(Boolean), }, - "onField": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(GraphQLBoolean), + "onField": &FieldConfig{ + Type: NewNonNull(Boolean), }, }, }) - __Schema = NewGraphQLObjectType(GraphQLObjectTypeConfig{ + __Schema = NewObject(ObjectConfig{ Name: "__Schema", Description: `A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query and mutation operations.`, - Fields: GraphQLFieldConfigMap{ - "types": &GraphQLFieldConfig{ + Fields: FieldConfigMap{ + "types": &FieldConfig{ Description: "A list of all types supported by this server.", - Type: NewGraphQLNonNull(NewGraphQLList( - NewGraphQLNonNull(__Type), + Type: NewNonNull(NewList( + NewNonNull(__Type), )), Resolve: func(p GQLFRParams) interface{} { - if schema, ok := p.Source.(GraphQLSchema); ok { - results := []GraphQLType{} + if schema, ok := p.Source.(Schema); ok { + results := []Type{} for _, ttype := range schema.GetTypeMap() { results = append(results, ttype) } return results } - return []GraphQLType{} + return []Type{} }, }, - "queryType": &GraphQLFieldConfig{ + "queryType": &FieldConfig{ Description: "The type that query operations will be rooted at.", - Type: NewGraphQLNonNull(__Type), + Type: NewNonNull(__Type), Resolve: func(p GQLFRParams) interface{} { - if schema, ok := p.Source.(GraphQLSchema); ok { + if schema, ok := p.Source.(Schema); ok { return schema.GetQueryType() } return nil }, }, - "mutationType": &GraphQLFieldConfig{ + "mutationType": &FieldConfig{ Description: `If this server supports mutation, the type that ` + `mutation operations will be rooted at.`, Type: __Type, Resolve: func(p GQLFRParams) interface{} { - if schema, ok := p.Source.(GraphQLSchema); ok { + if schema, ok := p.Source.(Schema); ok { if schema.GetMutationType() != nil { return schema.GetMutationType() } @@ -266,13 +266,13 @@ mutation operations.`, return nil }, }, - "directives": &GraphQLFieldConfig{ + "directives": &FieldConfig{ Description: `A list of all directives supported by this server.`, - Type: NewGraphQLNonNull(NewGraphQLList( - NewGraphQLNonNull(__Directive), + Type: NewNonNull(NewList( + NewNonNull(__Directive), )), Resolve: func(p GQLFRParams) interface{} { - if schema, ok := p.Source.(GraphQLSchema); ok { + if schema, ok := p.Source.(Schema); ok { return schema.GetDirectives() } return nil @@ -281,48 +281,48 @@ mutation operations.`, }, }) - __EnumValue = NewGraphQLObjectType(GraphQLObjectTypeConfig{ + __EnumValue = NewObject(ObjectConfig{ Name: "__EnumValue", - Fields: GraphQLFieldConfigMap{ - "name": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(GraphQLString), + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: NewNonNull(String), }, - "description": &GraphQLFieldConfig{ - Type: GraphQLString, + "description": &FieldConfig{ + Type: String, }, - "isDeprecated": &GraphQLFieldConfig{ - Type: NewGraphQLNonNull(GraphQLBoolean), + "isDeprecated": &FieldConfig{ + Type: NewNonNull(Boolean), Resolve: func(p GQLFRParams) interface{} { - if field, ok := p.Source.(*GraphQLEnumValueDefinition); ok { + if field, ok := p.Source.(*EnumValueDefinition); ok { return (field.DeprecationReason != "") } return false }, }, - "deprecationReason": &GraphQLFieldConfig{ - Type: GraphQLString, + "deprecationReason": &FieldConfig{ + Type: String, }, }, }) // Again, adding field configs to __Type that have cyclic reference here // because golang don't like them too much during init/compile-time - __Type.AddFieldConfig("fields", &GraphQLFieldConfig{ - Type: NewGraphQLList(NewGraphQLNonNull(__Field)), - Args: GraphQLFieldConfigArgumentMap{ - "includeDeprecated": &GraphQLArgumentConfig{ - Type: GraphQLBoolean, + __Type.AddFieldConfig("fields", &FieldConfig{ + Type: NewList(NewNonNull(__Field)), + Args: FieldConfigArgument{ + "includeDeprecated": &ArgumentConfig{ + Type: Boolean, DefaultValue: false, }, }, Resolve: func(p GQLFRParams) interface{} { includeDeprecated, _ := p.Args["includeDeprecated"].(bool) switch ttype := p.Source.(type) { - case *GraphQLObjectType: + case *Object: if ttype == nil { return nil } - fields := []*GraphQLFieldDefinition{} + fields := []*FieldDefinition{} for _, field := range ttype.GetFields() { if !includeDeprecated && field.DeprecationReason != "" { continue @@ -330,11 +330,11 @@ mutation operations.`, fields = append(fields, field) } return fields - case *GraphQLInterfaceType: + case *Interface: if ttype == nil { return nil } - fields := []*GraphQLFieldDefinition{} + fields := []*FieldDefinition{} for _, field := range ttype.GetFields() { if !includeDeprecated && field.DeprecationReason != "" { continue @@ -346,44 +346,44 @@ mutation operations.`, return nil }, }) - __Type.AddFieldConfig("interfaces", &GraphQLFieldConfig{ - Type: NewGraphQLList(NewGraphQLNonNull(__Type)), + __Type.AddFieldConfig("interfaces", &FieldConfig{ + Type: NewList(NewNonNull(__Type)), Resolve: func(p GQLFRParams) interface{} { switch ttype := p.Source.(type) { - case *GraphQLObjectType: + case *Object: return ttype.GetInterfaces() } return nil }, }) - __Type.AddFieldConfig("possibleTypes", &GraphQLFieldConfig{ - Type: NewGraphQLList(NewGraphQLNonNull(__Type)), + __Type.AddFieldConfig("possibleTypes", &FieldConfig{ + Type: NewList(NewNonNull(__Type)), Resolve: func(p GQLFRParams) interface{} { switch ttype := p.Source.(type) { - case *GraphQLInterfaceType: + case *Interface: return ttype.GetPossibleTypes() - case *GraphQLUnionType: + case *Union: return ttype.GetPossibleTypes() } return nil }, }) - __Type.AddFieldConfig("enumValues", &GraphQLFieldConfig{ - Type: NewGraphQLList(NewGraphQLNonNull(__EnumValue)), - Args: GraphQLFieldConfigArgumentMap{ - "includeDeprecated": &GraphQLArgumentConfig{ - Type: GraphQLBoolean, + __Type.AddFieldConfig("enumValues", &FieldConfig{ + Type: NewList(NewNonNull(__EnumValue)), + Args: FieldConfigArgument{ + "includeDeprecated": &ArgumentConfig{ + Type: Boolean, DefaultValue: false, }, }, Resolve: func(p GQLFRParams) interface{} { includeDeprecated, _ := p.Args["includeDeprecated"].(bool) switch ttype := p.Source.(type) { - case *GraphQLEnumType: + case *Enum: if includeDeprecated { return ttype.GetValues() } - values := []*GraphQLEnumValueDefinition{} + values := []*EnumValueDefinition{} for _, value := range ttype.GetValues() { if value.DeprecationReason != "" { continue @@ -395,11 +395,11 @@ mutation operations.`, return nil }, }) - __Type.AddFieldConfig("inputFields", &GraphQLFieldConfig{ - Type: NewGraphQLList(NewGraphQLNonNull(__InputValue)), + __Type.AddFieldConfig("inputFields", &FieldConfig{ + Type: NewList(NewNonNull(__InputValue)), Resolve: func(p GQLFRParams) interface{} { switch ttype := p.Source.(type) { - case *GraphQLInputObjectType: + case *InputObject: fields := []*InputObjectField{} for _, field := range ttype.GetFields() { fields = append(fields, field) @@ -409,32 +409,32 @@ mutation operations.`, return nil }, }) - __Type.AddFieldConfig("ofType", &GraphQLFieldConfig{ + __Type.AddFieldConfig("ofType", &FieldConfig{ Type: __Type, }) /** - * Note that these are GraphQLFieldDefinition and not GraphQLFieldConfig, + * Note that these are FieldDefinition and not FieldConfig, * so the format for args is different. */ - SchemaMetaFieldDef = &GraphQLFieldDefinition{ + SchemaMetaFieldDef = &FieldDefinition{ Name: "__schema", - Type: NewGraphQLNonNull(__Schema), + Type: NewNonNull(__Schema), Description: "Access the current type schema of this server.", - Args: []*GraphQLArgument{}, + Args: []*Argument{}, Resolve: func(p GQLFRParams) interface{} { return p.Info.Schema }, } - TypeMetaFieldDef = &GraphQLFieldDefinition{ + TypeMetaFieldDef = &FieldDefinition{ Name: "__type", Type: __Type, Description: "Request the type information of a single type.", - Args: []*GraphQLArgument{ - &GraphQLArgument{ + Args: []*Argument{ + &Argument{ Name: "name", - Type: NewGraphQLNonNull(GraphQLString), + Type: NewNonNull(String), }, }, Resolve: func(p GQLFRParams) interface{} { @@ -446,11 +446,11 @@ mutation operations.`, }, } - TypeNameMetaFieldDef = &GraphQLFieldDefinition{ + TypeNameMetaFieldDef = &FieldDefinition{ Name: "__typename", - Type: NewGraphQLNonNull(GraphQLString), + Type: NewNonNull(String), Description: "The name of the current Object type at runtime.", - Args: []*GraphQLArgument{}, + Args: []*Argument{}, Resolve: func(p GQLFRParams) interface{} { return p.Info.ParentType.GetName() }, @@ -473,9 +473,9 @@ mutation operations.`, * | Number | Int / Float | * */ -func astFromValue(value interface{}, ttype GraphQLType) ast.Value { +func astFromValue(value interface{}, ttype Type) ast.Value { - if ttype, ok := ttype.(*GraphQLNonNull); ok { + if ttype, ok := ttype.(*NonNull); ok { // Note: we're not checking that the result is non-null. // This function is not responsible for validating the input value. val := astFromValue(value, ttype.OfType) @@ -495,9 +495,9 @@ func astFromValue(value interface{}, ttype GraphQLType) ast.Value { return nil } - // Convert Golang slice to GraphQL list. If the GraphQLType is a list, but + // Convert Golang slice to GraphQL list. If the Type is a list, but // the value is not an array, convert the value using the list's item type. - if ttype, ok := ttype.(*GraphQLList); ok { + if ttype, ok := ttype.(*List); ok { if valueVal.Type().Kind() == reflect.Slice { itemType := ttype.OfType values := []ast.Value{} @@ -530,7 +530,7 @@ func astFromValue(value interface{}, ttype GraphQLType) ast.Value { }) } if value, ok := value.(int); ok { - if ttype == GraphQLFloat { + if ttype == Float { return ast.NewIntValue(&ast.IntValue{ Value: fmt.Sprintf("%v.0", value), }) @@ -551,7 +551,7 @@ func astFromValue(value interface{}, ttype GraphQLType) ast.Value { } if value, ok := value.(string); ok { - if _, ok := ttype.(*GraphQLEnumType); ok { + if _, ok := ttype.(*Enum); ok { return ast.NewEnumValue(&ast.EnumValue{ Value: fmt.Sprintf("%v", value), }) diff --git a/types/introspection_test.go b/types/introspection_test.go index 0c26d789..629e487c 100644 --- a/types/introspection_test.go +++ b/types/introspection_test.go @@ -10,26 +10,26 @@ import ( "testing" ) -func g(t *testing.T, p graphql.GraphqlParams) *types.GraphQLResult { - resultChannel := make(chan *types.GraphQLResult) +func g(t *testing.T, p graphql.Params) *types.Result { + resultChannel := make(chan *types.Result) go graphql.Graphql(p, resultChannel) result := <-resultChannel return result } func TestIntrospection_ExecutesAnIntrospectionQuery(t *testing.T) { - emptySchema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + emptySchema, err := types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "QueryRoot", - Fields: types.GraphQLFieldConfigMap{ - "onlyField": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "onlyField": &types.FieldConfig{ + Type: types.String, }, }, }), }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } expectedDataSubSet := map[string]interface{}{ "__schema": map[string]interface{}{ @@ -738,7 +738,7 @@ func TestIntrospection_ExecutesAnIntrospectionQuery(t *testing.T) { }, }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: emptySchema, RequestString: testutil.IntrospectionQuery, }) @@ -749,25 +749,25 @@ func TestIntrospection_ExecutesAnIntrospectionQuery(t *testing.T) { func TestIntrospection_ExecutesAnInputObject(t *testing.T) { - testInputObject := types.NewGraphQLInputObjectType(types.InputObjectConfig{ + testInputObject := types.NewInputObject(types.InputObjectConfig{ Name: "TestInputObject", Fields: types.InputObjectConfigFieldMap{ "a": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, DefaultValue: "foo", }, "b": &types.InputObjectFieldConfig{ - Type: types.NewGraphQLList(types.GraphQLString), + Type: types.NewList(types.String), }, }, }) - testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + testType := types.NewObject(types.ObjectConfig{ Name: "TestType", - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "complex": &types.GraphQLArgumentConfig{ + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "complex": &types.ArgumentConfig{ Type: testInputObject, }, }, @@ -777,11 +777,11 @@ func TestIntrospection_ExecutesAnInputObject(t *testing.T) { }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: testType, }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } query := ` { @@ -850,7 +850,7 @@ func TestIntrospection_ExecutesAnInputObject(t *testing.T) { }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: schema, RequestString: query, }) @@ -861,19 +861,19 @@ func TestIntrospection_ExecutesAnInputObject(t *testing.T) { func TestIntrospection_SupportsThe__TypeRootField(t *testing.T) { - testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + testType := types.NewObject(types.ObjectConfig{ Name: "TestType", - Fields: types.GraphQLFieldConfigMap{ - "testField": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "testField": &types.FieldConfig{ + Type: types.String, }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: testType, }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } query := ` { @@ -882,14 +882,14 @@ func TestIntrospection_SupportsThe__TypeRootField(t *testing.T) { } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestType", }, }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: schema, RequestString: query, }) @@ -899,23 +899,23 @@ func TestIntrospection_SupportsThe__TypeRootField(t *testing.T) { } func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) { - testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + testType := types.NewObject(types.ObjectConfig{ Name: "TestType", - Fields: types.GraphQLFieldConfigMap{ - "nonDeprecated": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "nonDeprecated": &types.FieldConfig{ + Type: types.String, }, - "deprecated": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "deprecated": &types.FieldConfig{ + Type: types.String, DeprecationReason: "Removed in 1.0", }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: testType, }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } query := ` { @@ -929,7 +929,7 @@ func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) { } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestType", @@ -948,7 +948,7 @@ func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) { }, }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: schema, RequestString: query, }) @@ -958,23 +958,23 @@ func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) { } func TestIntrospection_RespectsTheIncludeDeprecatedParameterForFields(t *testing.T) { - testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + testType := types.NewObject(types.ObjectConfig{ Name: "TestType", - Fields: types.GraphQLFieldConfigMap{ - "nonDeprecated": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "nonDeprecated": &types.FieldConfig{ + Type: types.String, }, - "deprecated": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "deprecated": &types.FieldConfig{ + Type: types.String, DeprecationReason: "Removed in 1.0", }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: testType, }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } query := ` { @@ -992,7 +992,7 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForFields(t *testing } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestType", @@ -1017,7 +1017,7 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForFields(t *testing }, }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: schema, RequestString: query, }) @@ -1027,34 +1027,34 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForFields(t *testing } func TestIntrospection_IdentifiesDeprecatedEnumValues(t *testing.T) { - testEnum := types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ + testEnum := types.NewEnum(types.EnumConfig{ Name: "TestEnum", - Values: types.GraphQLEnumValueConfigMap{ - "NONDEPRECATED": &types.GraphQLEnumValueConfig{ + Values: types.EnumValueConfigMap{ + "NONDEPRECATED": &types.EnumValueConfig{ Value: 0, }, - "DEPRECATED": &types.GraphQLEnumValueConfig{ + "DEPRECATED": &types.EnumValueConfig{ Value: 1, DeprecationReason: "Removed in 1.0", }, - "ALSONONDEPRECATED": &types.GraphQLEnumValueConfig{ + "ALSONONDEPRECATED": &types.EnumValueConfig{ Value: 2, }, }, }) - testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + testType := types.NewObject(types.ObjectConfig{ Name: "TestType", - Fields: types.GraphQLFieldConfigMap{ - "testEnum": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "testEnum": &types.FieldConfig{ Type: testEnum, }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: testType, }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } query := ` { @@ -1068,7 +1068,7 @@ func TestIntrospection_IdentifiesDeprecatedEnumValues(t *testing.T) { } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestEnum", @@ -1092,7 +1092,7 @@ func TestIntrospection_IdentifiesDeprecatedEnumValues(t *testing.T) { }, }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: schema, RequestString: query, }) @@ -1102,34 +1102,34 @@ func TestIntrospection_IdentifiesDeprecatedEnumValues(t *testing.T) { } func TestIntrospection_RespectsTheIncludeDeprecatedParameterForEnumValues(t *testing.T) { - testEnum := types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ + testEnum := types.NewEnum(types.EnumConfig{ Name: "TestEnum", - Values: types.GraphQLEnumValueConfigMap{ - "NONDEPRECATED": &types.GraphQLEnumValueConfig{ + Values: types.EnumValueConfigMap{ + "NONDEPRECATED": &types.EnumValueConfig{ Value: 0, }, - "DEPRECATED": &types.GraphQLEnumValueConfig{ + "DEPRECATED": &types.EnumValueConfig{ Value: 1, DeprecationReason: "Removed in 1.0", }, - "ALSONONDEPRECATED": &types.GraphQLEnumValueConfig{ + "ALSONONDEPRECATED": &types.EnumValueConfig{ Value: 2, }, }, }) - testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + testType := types.NewObject(types.ObjectConfig{ Name: "TestType", - Fields: types.GraphQLFieldConfigMap{ - "testEnum": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "testEnum": &types.FieldConfig{ Type: testEnum, }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: testType, }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } query := ` { @@ -1147,7 +1147,7 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForEnumValues(t *tes } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestEnum", @@ -1181,7 +1181,7 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForEnumValues(t *tes }, }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: schema, RequestString: query, }) @@ -1191,19 +1191,19 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForEnumValues(t *tes } func TestIntrospection_FailsAsExpectedOnThe__TypeRootFieldWithoutAnArg(t *testing.T) { - testType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + testType := types.NewObject(types.ObjectConfig{ Name: "TestType", - Fields: types.GraphQLFieldConfigMap{ - "testField": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "testField": &types.FieldConfig{ + Type: types.String, }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: testType, }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } query := ` { @@ -1212,9 +1212,9 @@ func TestIntrospection_FailsAsExpectedOnThe__TypeRootFieldWithoutAnArg(t *testin } } ` - expected := &types.GraphQLResult{ - Errors: []graphqlerrors.GraphQLFormattedError{ - graphqlerrors.GraphQLFormattedError{ + expected := &types.Result{ + Errors: []graphqlerrors.FormattedError{ + graphqlerrors.FormattedError{ Message: `Field "__type" argument "name" of type "String!" ` + `is required but not provided.`, Locations: []location.SourceLocation{ @@ -1223,7 +1223,7 @@ func TestIntrospection_FailsAsExpectedOnThe__TypeRootFieldWithoutAnArg(t *testin }, }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: schema, RequestString: query, }) @@ -1235,19 +1235,19 @@ func TestIntrospection_FailsAsExpectedOnThe__TypeRootFieldWithoutAnArg(t *testin func TestIntrospection_ExposesDescriptionsOnTypesAndFields(t *testing.T) { - queryRoot := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + queryRoot := types.NewObject(types.ObjectConfig{ Name: "QueryRoot", - Fields: types.GraphQLFieldConfigMap{ - "onlyField": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "onlyField": &types.FieldConfig{ + Type: types.String, }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: queryRoot, }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } query := ` { @@ -1261,7 +1261,7 @@ func TestIntrospection_ExposesDescriptionsOnTypesAndFields(t *testing.T) { } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "schemaType": map[string]interface{}{ "name": "__Schema", @@ -1291,7 +1291,7 @@ mutation operations.`, }, }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: schema, RequestString: query, }) @@ -1301,19 +1301,19 @@ mutation operations.`, } func TestIntrospection_ExposesDescriptionsOnEnums(t *testing.T) { - queryRoot := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + queryRoot := types.NewObject(types.ObjectConfig{ Name: "QueryRoot", - Fields: types.GraphQLFieldConfigMap{ - "onlyField": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "onlyField": &types.FieldConfig{ + Type: types.String, }, }, }) - schema, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + schema, err := types.NewSchema(types.SchemaConfig{ Query: queryRoot, }) if err != nil { - t.Fatalf("Error creating GraphQLSchema: %v", err.Error()) + t.Fatalf("Error creating Schema: %v", err.Error()) } query := ` { @@ -1327,7 +1327,7 @@ func TestIntrospection_ExposesDescriptionsOnEnums(t *testing.T) { } } ` - expected := &types.GraphQLResult{ + expected := &types.Result{ Data: map[string]interface{}{ "typeKindType": map[string]interface{}{ "name": "__TypeKind", @@ -1369,7 +1369,7 @@ func TestIntrospection_ExposesDescriptionsOnEnums(t *testing.T) { }, }, } - result := g(t, graphql.GraphqlParams{ + result := g(t, graphql.Params{ Schema: schema, RequestString: query, }) diff --git a/types/scalars.go b/types/scalars.go index b3574c15..bec1b3b1 100644 --- a/types/scalars.go +++ b/types/scalars.go @@ -45,7 +45,7 @@ func intOrNil(value int) interface{} { return nil } -var GraphQLInt *GraphQLScalarType = NewGraphQLScalarType(GraphQLScalarTypeConfig{ +var Int *Scalar = NewScalar(ScalarConfig{ Name: "Int", Serialize: coerceInt, ParseValue: coerceInt, @@ -83,7 +83,7 @@ func coerceFloat32(value interface{}) interface{} { return float32(0) } -var GraphQLFloat *GraphQLScalarType = NewGraphQLScalarType(GraphQLScalarTypeConfig{ +var Float *Scalar = NewScalar(ScalarConfig{ Name: "Float", Serialize: coerceFloat32, ParseValue: coerceFloat32, @@ -106,7 +106,7 @@ func coerceString(value interface{}) interface{} { return fmt.Sprintf("%v", value) } -var GraphQLString *GraphQLScalarType = NewGraphQLScalarType(GraphQLScalarTypeConfig{ +var String *Scalar = NewScalar(ScalarConfig{ Name: "String", Serialize: coerceString, ParseValue: coerceString, @@ -148,7 +148,7 @@ func coerceBool(value interface{}) interface{} { return false } -var GraphQLBoolean *GraphQLScalarType = NewGraphQLScalarType(GraphQLScalarTypeConfig{ +var Boolean *Scalar = NewScalar(ScalarConfig{ Name: "Boolean", Serialize: coerceBool, ParseValue: coerceBool, @@ -161,7 +161,7 @@ var GraphQLBoolean *GraphQLScalarType = NewGraphQLScalarType(GraphQLScalarTypeCo }, }) -var GraphQLID *GraphQLScalarType = NewGraphQLScalarType(GraphQLScalarTypeConfig{ +var ID *Scalar = NewScalar(ScalarConfig{ Name: "ID", Serialize: coerceString, ParseValue: coerceString, diff --git a/types/scalars_serialization_test.go b/types/scalars_serialization_test.go index ae3de172..0d86f5d4 100644 --- a/types/scalars_serialization_test.go +++ b/types/scalars_serialization_test.go @@ -44,10 +44,10 @@ func TestTypeSystem_Scalar_SerializesOutputInt(t *testing.T) { } for _, test := range tests { - val := GraphQLInt.Serialize(test.Value) + val := Int.Serialize(test.Value) if val != test.Expected { reflectedValue := reflect.ValueOf(test.Value) - t.Fatalf("Failed GraphQLInt.Serialize(%v(%v)), expected: %v, got %v", reflectedValue.Type(), test.Value, test.Expected, val) + t.Fatalf("Failed Int.Serialize(%v(%v)), expected: %v, got %v", reflectedValue.Type(), test.Value, test.Expected, val) } } } @@ -67,10 +67,10 @@ func TestTypeSystem_Scalar_SerializesOutputFloat(t *testing.T) { } for i, test := range tests { - val := GraphQLFloat.Serialize(test.Value) + val := Float.Serialize(test.Value) if val != test.Expected { reflectedValue := reflect.ValueOf(test.Value) - t.Fatalf("Failed test #%d - GraphQLFloat.Serialize(%v(%v)), expected: %v, got %v", i, reflectedValue.Type(), test.Value, test.Expected, val) + t.Fatalf("Failed test #%d - Float.Serialize(%v(%v)), expected: %v, got %v", i, reflectedValue.Type(), test.Value, test.Expected, val) } } } @@ -85,10 +85,10 @@ func TestTypeSystem_Scalar_SerializesOutputStrings(t *testing.T) { } for _, test := range tests { - val := GraphQLString.Serialize(test.Value) + val := String.Serialize(test.Value) if val != test.Expected { reflectedValue := reflect.ValueOf(test.Value) - t.Fatalf("Failed GraphQLString.Serialize(%v(%v)), expected: %v, got %v", reflectedValue.Type(), test.Value, test.Expected, val) + t.Fatalf("Failed String.Serialize(%v(%v)), expected: %v, got %v", reflectedValue.Type(), test.Value, test.Expected, val) } } } @@ -106,10 +106,10 @@ func TestTypeSystem_Scalar_SerializesOutputBoolean(t *testing.T) { } for _, test := range tests { - val := GraphQLBoolean.Serialize(test.Value) + val := Boolean.Serialize(test.Value) if val != test.Expected { reflectedValue := reflect.ValueOf(test.Value) - t.Fatalf("Failed GraphQLString.GraphQLBoolean(%v(%v)), expected: %v, got %v", reflectedValue.Type(), test.Value, test.Expected, val) + t.Fatalf("Failed String.Boolean(%v(%v)), expected: %v, got %v", reflectedValue.Type(), test.Value, test.Expected, val) } } } diff --git a/types/schema.go b/types/schema.go index 90142abb..d834b830 100644 --- a/types/schema.go +++ b/types/schema.go @@ -10,29 +10,29 @@ A Schema is created by supplying the root types of each type of operation, query and mutation (optional). A schema definition is then supplied to the validator and executor. Example: - myAppSchema, err := NewGraphQLSchema(GraphQLSchemaConfig({ + myAppSchema, err := NewSchema(SchemaConfig({ Query: MyAppQueryRootType Mutation: MyAppMutationRootType }); */ -type GraphQLSchemaConfig struct { - Query *GraphQLObjectType - Mutation *GraphQLObjectType +type SchemaConfig struct { + Query *Object + Mutation *Object } -// chose to name as GraphQLTypeMap instead of TypeMap -type GraphQLTypeMap map[string]GraphQLType +// chose to name as TypeMap instead of TypeMap +type TypeMap map[string]Type -type GraphQLSchema struct { - schemaConfig GraphQLSchemaConfig - typeMap GraphQLTypeMap - directives []*GraphQLDirective +type Schema struct { + schemaConfig SchemaConfig + typeMap TypeMap + directives []*Directive } -func NewGraphQLSchema(config GraphQLSchemaConfig) (GraphQLSchema, error) { +func NewSchema(config SchemaConfig) (Schema, error) { var err error - schema := GraphQLSchema{} + schema := Schema{} err = invariant(config.Query != nil, "Schema query must be Object Type but got: nil.") if err != nil { @@ -50,8 +50,8 @@ func NewGraphQLSchema(config GraphQLSchemaConfig) (GraphQLSchema, error) { schema.schemaConfig = config // Build type map now to detect any errors within this schema. - typeMap := GraphQLTypeMap{} - objectTypes := []*GraphQLObjectType{ + typeMap := TypeMap{} + objectTypes := []*Object{ schema.GetQueryType(), schema.GetMutationType(), __Type, @@ -73,7 +73,7 @@ func NewGraphQLSchema(config GraphQLSchemaConfig) (GraphQLSchema, error) { // Enforce correct interface implementations for _, ttype := range typeMap { switch ttype := ttype.(type) { - case *GraphQLObjectType: + case *Object: for _, iface := range ttype.GetInterfaces() { err := assertObjectImplementsInterface(ttype, iface) if err != nil { @@ -86,48 +86,48 @@ func NewGraphQLSchema(config GraphQLSchemaConfig) (GraphQLSchema, error) { return schema, nil } -func (gq *GraphQLSchema) GetQueryType() *GraphQLObjectType { +func (gq *Schema) GetQueryType() *Object { return gq.schemaConfig.Query } -func (gq *GraphQLSchema) GetMutationType() *GraphQLObjectType { +func (gq *Schema) GetMutationType() *Object { return gq.schemaConfig.Mutation } -func (gq *GraphQLSchema) GetDirectives() []*GraphQLDirective { +func (gq *Schema) GetDirectives() []*Directive { if len(gq.directives) == 0 { - gq.directives = []*GraphQLDirective{ - GraphQLIncludeDirective, - GraphQLSkipDirective, + gq.directives = []*Directive{ + IncludeDirective, + SkipDirective, } } return gq.directives } -func (gq *GraphQLSchema) GetTypeMap() GraphQLTypeMap { +func (gq *Schema) GetTypeMap() TypeMap { return gq.typeMap } -func (gq *GraphQLSchema) GetType(name string) GraphQLType { +func (gq *Schema) GetType(name string) Type { return gq.GetTypeMap()[name] } -func typeMapReducer(typeMap GraphQLTypeMap, objectType GraphQLType) (GraphQLTypeMap, error) { +func typeMapReducer(typeMap TypeMap, objectType Type) (TypeMap, error) { var err error if objectType == nil || objectType.GetName() == "" { return typeMap, nil } switch objectType := objectType.(type) { - case *GraphQLList: + case *List: if objectType.OfType != nil { return typeMapReducer(typeMap, objectType.OfType) } - case *GraphQLNonNull: + case *NonNull: if objectType.OfType != nil { return typeMapReducer(typeMap, objectType.OfType) } - case *GraphQLObjectType: + case *Object: if objectType.err != nil { return typeMap, objectType.err } @@ -150,7 +150,7 @@ func typeMapReducer(typeMap GraphQLTypeMap, objectType GraphQLType) (GraphQLType typeMap[objectType.GetName()] = objectType switch objectType := objectType.(type) { - case *GraphQLUnionType: + case *Union: types := objectType.GetPossibleTypes() if objectType.err != nil { return typeMap, objectType.err @@ -164,7 +164,7 @@ func typeMapReducer(typeMap GraphQLTypeMap, objectType GraphQLType) (GraphQLType return typeMap, err } } - case *GraphQLInterfaceType: + case *Interface: types := objectType.GetPossibleTypes() if objectType.err != nil { return typeMap, objectType.err @@ -178,7 +178,7 @@ func typeMapReducer(typeMap GraphQLTypeMap, objectType GraphQLType) (GraphQLType return typeMap, err } } - case *GraphQLObjectType: + case *Object: interfaces := objectType.GetInterfaces() if objectType.err != nil { return typeMap, objectType.err @@ -195,7 +195,7 @@ func typeMapReducer(typeMap GraphQLTypeMap, objectType GraphQLType) (GraphQLType } switch objectType := objectType.(type) { - case *GraphQLObjectType: + case *Object: fieldMap := objectType.GetFields() if objectType.err != nil { return typeMap, objectType.err @@ -212,7 +212,7 @@ func typeMapReducer(typeMap GraphQLTypeMap, objectType GraphQLType) (GraphQLType return typeMap, err } } - case *GraphQLInterfaceType: + case *Interface: fieldMap := objectType.GetFields() if objectType.err != nil { return typeMap, objectType.err @@ -229,7 +229,7 @@ func typeMapReducer(typeMap GraphQLTypeMap, objectType GraphQLType) (GraphQLType return typeMap, err } } - case *GraphQLInputObjectType: + case *InputObject: fieldMap := objectType.GetFields() if objectType.err != nil { return typeMap, objectType.err @@ -244,7 +244,7 @@ func typeMapReducer(typeMap GraphQLTypeMap, objectType GraphQLType) (GraphQLType return typeMap, nil } -func assertObjectImplementsInterface(object *GraphQLObjectType, iface *GraphQLInterfaceType) error { +func assertObjectImplementsInterface(object *Object, iface *Interface) error { objectFieldMap := object.GetFields() ifaceFieldMap := iface.GetFields() @@ -278,7 +278,7 @@ func assertObjectImplementsInterface(object *GraphQLObjectType, iface *GraphQLIn // Assert each interface field arg is implemented. for _, ifaceArg := range ifaceField.Args { argName := ifaceArg.Name - var objectArg *GraphQLArgument + var objectArg *Argument for _, arg := range objectField.Args { if arg.Name == argName { objectArg = arg @@ -315,7 +315,7 @@ func assertObjectImplementsInterface(object *GraphQLObjectType, iface *GraphQLIn // Assert argument set invariance. for _, objectArg := range objectField.Args { argName := objectArg.Name - var ifaceArg *GraphQLArgument + var ifaceArg *Argument for _, arg := range ifaceField.Args { if arg.Name == argName { ifaceArg = arg @@ -337,14 +337,14 @@ func assertObjectImplementsInterface(object *GraphQLObjectType, iface *GraphQLIn return nil } -func isEqualType(typeA GraphQLType, typeB GraphQLType) bool { - if typeA, ok := typeA.(*GraphQLNonNull); ok { - if typeB, ok := typeB.(*GraphQLNonNull); ok { +func isEqualType(typeA Type, typeB Type) bool { + if typeA, ok := typeA.(*NonNull); ok { + if typeB, ok := typeB.(*NonNull); ok { return isEqualType(typeA.OfType, typeB.OfType) } } - if typeA, ok := typeA.(*GraphQLList); ok { - if typeB, ok := typeB.(*GraphQLList); ok { + if typeA, ok := typeA.(*List); ok { + if typeB, ok := typeB.(*List); ok { return isEqualType(typeA.OfType, typeB.OfType) } } diff --git a/types/types.go b/types/types.go index 98fb8394..36f66c5f 100644 --- a/types/types.go +++ b/types/types.go @@ -4,13 +4,13 @@ import ( "github.com/chris-ramon/graphql/errors" ) -type Schema interface{} +// type Schema interface{} -type GraphQLResult struct { +type Result struct { Data interface{} `json:"data"` - Errors []graphqlerrors.GraphQLFormattedError `json:"errors,omitempty"` + Errors []graphqlerrors.FormattedError `json:"errors,omitempty"` } -func (gqR *GraphQLResult) HasErrors() bool { +func (gqR *Result) HasErrors() bool { return (len(gqR.Errors) > 0) } diff --git a/types/validation_test.go b/types/validation_test.go index 645b0b98..266c3519 100644 --- a/types/validation_test.go +++ b/types/validation_test.go @@ -7,7 +7,7 @@ import ( "github.com/chris-ramon/graphql/types" ) -var someScalarType = types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ +var someScalarType = types.NewScalar(types.ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil @@ -19,111 +19,111 @@ var someScalarType = types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ return nil }, }) -var someObjectType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var someObjectType = types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) -var objectWithIsTypeOf = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +var objectWithIsTypeOf = types.NewObject(types.ObjectConfig{ Name: "ObjectWithIsTypeOf", - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { return true }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) -var someUnionType = types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ +var someUnionType = types.NewUnion(types.UnionConfig{ Name: "SomeUnion", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Types: []*types.GraphQLObjectType{ + Types: []*types.Object{ someObjectType, }, }) -var someInterfaceType = types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ +var someInterfaceType = types.NewInterface(types.InterfaceConfig{ Name: "SomeInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) -var someEnumType = types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ +var someEnumType = types.NewEnum(types.EnumConfig{ Name: "SomeEnum", - Values: types.GraphQLEnumValueConfigMap{ - "ONLY": &types.GraphQLEnumValueConfig{}, + Values: types.EnumValueConfigMap{ + "ONLY": &types.EnumValueConfig{}, }, }) -var someInputObject = types.NewGraphQLInputObjectType(types.InputObjectConfig{ +var someInputObject = types.NewInputObject(types.InputObjectConfig{ Name: "SomeInputObject", Fields: types.InputObjectConfigFieldMap{ "f": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, DefaultValue: "Hello", }, }, }) -func withModifiers(ttypes []types.GraphQLType) []types.GraphQLType { +func withModifiers(ttypes []types.Type) []types.Type { res := ttypes for _, ttype := range ttypes { - res = append(res, types.NewGraphQLList(ttype)) + res = append(res, types.NewList(ttype)) } for _, ttype := range ttypes { - res = append(res, types.NewGraphQLNonNull(ttype)) + res = append(res, types.NewNonNull(ttype)) } for _, ttype := range ttypes { - res = append(res, types.NewGraphQLNonNull(types.NewGraphQLList(ttype))) + res = append(res, types.NewNonNull(types.NewList(ttype))) } return res } -var outputTypes = withModifiers([]types.GraphQLType{ - types.GraphQLString, +var outputTypes = withModifiers([]types.Type{ + types.String, someScalarType, someEnumType, someObjectType, someUnionType, someInterfaceType, }) -var inputTypes = withModifiers([]types.GraphQLType{ - types.GraphQLString, +var inputTypes = withModifiers([]types.Type{ + types.String, someScalarType, someEnumType, someInputObject, }) -func schemaWithFieldType(ttype types.GraphQLOutputType) (types.GraphQLSchema, error) { - return types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +func schemaWithFieldType(ttype types.Output) (types.Schema, error) { + return types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ Type: ttype, }, }, }), }) } -func schemaWithInputObject(ttype types.GraphQLInputType) (types.GraphQLSchema, error) { - return types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ +func schemaWithInputObject(ttype types.Input) (types.Schema, error) { + return types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "args": &types.GraphQLArgumentConfig{ + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "args": &types.ArgumentConfig{ Type: ttype, }, }, @@ -132,119 +132,119 @@ func schemaWithInputObject(ttype types.GraphQLInputType) (types.GraphQLSchema, e }), }) } -func schemaWithObjectFieldOfType(fieldType types.GraphQLInputType) (types.GraphQLSchema, error) { +func schemaWithObjectFieldOfType(fieldType types.Input) (types.Schema, error) { - badObjectType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + badObjectType := types.NewObject(types.ObjectConfig{ Name: "BadObject", - Fields: types.GraphQLFieldConfigMap{ - "badField": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "badField": &types.FieldConfig{ Type: fieldType, }, }, }) - return types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + return types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ Type: badObjectType, }, }, }), }) } -func schemaWithObjectImplementingType(implementedType *types.GraphQLInterfaceType) (types.GraphQLSchema, error) { +func schemaWithObjectImplementingType(implementedType *types.Interface) (types.Schema, error) { - badObjectType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + badObjectType := types.NewObject(types.ObjectConfig{ Name: "BadObject", - Interfaces: []*types.GraphQLInterfaceType{implementedType}, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Interfaces: []*types.Interface{implementedType}, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - return types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + return types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ Type: badObjectType, }, }, }), }) } -func schemaWithUnionOfType(ttype *types.GraphQLObjectType) (types.GraphQLSchema, error) { +func schemaWithUnionOfType(ttype *types.Object) (types.Schema, error) { - badObjectType := types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + badObjectType := types.NewUnion(types.UnionConfig{ Name: "BadUnion", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Types: []*types.GraphQLObjectType{ttype}, + Types: []*types.Object{ttype}, }) - return types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + return types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ Type: badObjectType, }, }, }), }) } -func schemaWithInterfaceFieldOfType(ttype types.GraphQLType) (types.GraphQLSchema, error) { +func schemaWithInterfaceFieldOfType(ttype types.Type) (types.Schema, error) { - badInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + badInterfaceType := types.NewInterface(types.InterfaceConfig{ Name: "BadInterface", - Fields: types.GraphQLFieldConfigMap{ - "badField": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "badField": &types.FieldConfig{ Type: ttype, }, }, }) - return types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + return types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ Type: badInterfaceType, }, }, }), }) } -func schemaWithArgOfType(ttype types.GraphQLType) (types.GraphQLSchema, error) { +func schemaWithArgOfType(ttype types.Type) (types.Schema, error) { - badObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + badObject := types.NewObject(types.ObjectConfig{ Name: "BadObject", - Fields: types.GraphQLFieldConfigMap{ - "badField": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "badArg": &types.GraphQLArgumentConfig{ + Fields: types.FieldConfigMap{ + "badField": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "badArg": &types.ArgumentConfig{ Type: ttype, }, }, }, }, }) - return types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + return types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ Type: badObject, }, }, }), }) } -func schemaWithInputFieldOfType(ttype types.GraphQLType) (types.GraphQLSchema, error) { +func schemaWithInputFieldOfType(ttype types.Type) (types.Schema, error) { - badInputObject := types.NewGraphQLInputObjectType(types.InputObjectConfig{ + badInputObject := types.NewInputObject(types.InputObjectConfig{ Name: "BadInputObject", Fields: types.InputObjectConfigFieldMap{ "badField": &types.InputObjectFieldConfig{ @@ -252,14 +252,14 @@ func schemaWithInputFieldOfType(ttype types.GraphQLType) (types.GraphQLSchema, e }, }, }) - return types.NewGraphQLSchema(types.GraphQLSchemaConfig{ - Query: types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + return types.NewSchema(types.SchemaConfig{ + Query: types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "badArg": &types.GraphQLArgumentConfig{ + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "badArg": &types.ArgumentConfig{ Type: badInputObject, }, }, @@ -270,7 +270,7 @@ func schemaWithInputFieldOfType(ttype types.GraphQLType) (types.GraphQLSchema, e } func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryTypeIsAnObjectType(t *testing.T) { - _, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + _, err := types.NewSchema(types.SchemaConfig{ Query: someObjectType, }) if err != nil { @@ -278,15 +278,15 @@ func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryTypeIs } } func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryAndMutationTypesAreObjectType(t *testing.T) { - mutationObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + mutationObject := types.NewObject(types.ObjectConfig{ Name: "Mutation", - Fields: types.GraphQLFieldConfigMap{ - "edit": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "edit": &types.FieldConfig{ + Type: types.String, }, }, }) - _, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + _, err := types.NewSchema(types.SchemaConfig{ Query: someObjectType, Mutation: mutationObject, }) @@ -295,7 +295,7 @@ func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryAndMut } } func TestTypeSystem_SchemaMustHaveObjectRootTypes_RejectsASchemaWithoutAQueryType(t *testing.T) { - _, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{}) + _, err := types.NewSchema(types.SchemaConfig{}) expectedError := "Schema query must be Object Type but got: nil." if err == nil || err.Error() != expectedError { t.Fatalf("Expected error: %v, got %v", expectedError, err) @@ -304,24 +304,24 @@ func TestTypeSystem_SchemaMustHaveObjectRootTypes_RejectsASchemaWithoutAQueryTyp func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichRedefinesABuiltInType(t *testing.T) { - fakeString := types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ + fakeString := types.NewScalar(types.ScalarConfig{ Name: "String", Serialize: func(value interface{}) interface{} { return nil }, }) - queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + queryType := types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "normal": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "normal": &types.FieldConfig{ + Type: types.String, }, - "fake": &types.GraphQLFieldConfig{ + "fake": &types.FieldConfig{ Type: fakeString, }, }, }) - _, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + _, err := types.NewSchema(types.SchemaConfig{ Query: queryType, }) expectedError := `Schema must contain unique named types but contains multiple types named "String".` @@ -331,34 +331,34 @@ func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichRedef } func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichDefinesAnObjectTypeTwice(t *testing.T) { - a := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + a := types.NewObject(types.ObjectConfig{ Name: "SameName", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - b := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + b := types.NewObject(types.ObjectConfig{ Name: "SameName", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + queryType := types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "a": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "a": &types.FieldConfig{ Type: a, }, - "b": &types.GraphQLFieldConfig{ + "b": &types.FieldConfig{ Type: b, }, }, }) - _, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + _, err := types.NewSchema(types.SchemaConfig{ Query: queryType, }) expectedError := `Schema must contain unique named types but contains multiple types named "SameName".` @@ -368,48 +368,48 @@ func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichDefin } func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichHaveSameNamedObjectsImplementingAnInterface(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - _ = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _ = types.NewObject(types.ObjectConfig{ Name: "BadObject", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ anotherInterface, }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - _ = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _ = types.NewObject(types.ObjectConfig{ Name: "BadObject", - Interfaces: []*types.GraphQLInterfaceType{ + Interfaces: []*types.Interface{ anotherInterface, }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + queryType := types.NewObject(types.ObjectConfig{ Name: "Query", - Fields: types.GraphQLFieldConfigMap{ - "iface": &types.GraphQLFieldConfig{ + Fields: types.FieldConfigMap{ + "iface": &types.FieldConfig{ Type: anotherInterface, }, }, }) - _, err := types.NewGraphQLSchema(types.GraphQLSchemaConfig{ + _, err := types.NewSchema(types.SchemaConfig{ Query: queryType, }) expectedError := `Schema must contain unique named types but contains multiple types named "BadObject".` @@ -419,11 +419,11 @@ func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichHaveS } func TestTypeSystem_ObjectsMustHaveFields_AcceptsAnObjectTypeWithFieldsObject(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, })) @@ -432,7 +432,7 @@ func TestTypeSystem_ObjectsMustHaveFields_AcceptsAnObjectTypeWithFieldsObject(t } } func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithMissingFields(t *testing.T) { - badObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + badObject := types.NewObject(types.ObjectConfig{ Name: "SomeObject", }) _, err := schemaWithFieldType(badObject) @@ -442,11 +442,11 @@ func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithMissingFields(t } } func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithIncorrectlyNamedFields(t *testing.T) { - badObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + badObject := types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Fields: types.GraphQLFieldConfigMap{ - "bad-name-with-dashes": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "bad-name-with-dashes": &types.FieldConfig{ + Type: types.String, }, }, }) @@ -457,9 +457,9 @@ func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithIncorrectlyName } } func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithEmptyFields(t *testing.T) { - badObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + badObject := types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Fields: types.GraphQLFieldConfigMap{}, + Fields: types.FieldConfigMap{}, }) _, err := schemaWithFieldType(badObject) expectedError := `SomeObject fields must be an object with field names as keys or a function which return such an object.` @@ -469,14 +469,14 @@ func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithEmptyFields(t * } func TestTypeSystem_FieldsArgsMustBeProperlyNamed_AcceptsFieldArgsWithValidNames(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Fields: types.GraphQLFieldConfigMap{ - "goodField": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "goodArgs": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "goodField": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "goodArgs": &types.ArgumentConfig{ + Type: types.String, }, }, }, @@ -487,14 +487,14 @@ func TestTypeSystem_FieldsArgsMustBeProperlyNamed_AcceptsFieldArgsWithValidNames } } func TestTypeSystem_FieldsArgsMustBeProperlyNamed_RejectsFieldArgWithInvalidNames(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Fields: types.GraphQLFieldConfigMap{ - "badField": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "bad-name-with-dashes": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "badField": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "bad-name-with-dashes": &types.ArgumentConfig{ + Type: types.String, }, }, }, @@ -507,14 +507,14 @@ func TestTypeSystem_FieldsArgsMustBeProperlyNamed_RejectsFieldArgWithInvalidName } func TestTypeSystem_FieldsArgsMustBeObjects_AcceptsAnObjectTypeWithFieldArgs(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Fields: types.GraphQLFieldConfigMap{ - "goodField": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "goodArgs": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "goodField": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "goodArgs": &types.ArgumentConfig{ + Type: types.String, }, }, }, @@ -526,25 +526,25 @@ func TestTypeSystem_FieldsArgsMustBeObjects_AcceptsAnObjectTypeWithFieldArgs(t * } func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithArrayInterfaces(t *testing.T) { - anotherInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Interfaces: (types.GraphQLInterfacesThunk)(func() []*types.GraphQLInterfaceType { - return []*types.GraphQLInterfaceType{anotherInterfaceType} + Interfaces: (types.InterfacesThunk)(func() []*types.Interface { + return []*types.Interface{anotherInterfaceType} }), - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, })) @@ -554,23 +554,23 @@ func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithArrayInte } func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithInterfacesAsFunctionReturningAnArray(t *testing.T) { - anotherInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterfaceType}, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Interfaces: []*types.Interface{anotherInterfaceType}, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, })) @@ -580,12 +580,12 @@ func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithInterface } func TestTypeSystem_UnionTypesMustBeArray_AcceptsAUnionTypeWithArrayTypes(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ Name: "SomeUnion", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Types: []*types.GraphQLObjectType{ + Types: []*types.Object{ someObjectType, }, })) @@ -594,9 +594,9 @@ func TestTypeSystem_UnionTypesMustBeArray_AcceptsAUnionTypeWithArrayTypes(t *tes } } func TestTypeSystem_UnionTypesMustBeArray_RejectsAUnionTypeWithoutTypes(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ Name: "SomeUnion", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, })) @@ -606,12 +606,12 @@ func TestTypeSystem_UnionTypesMustBeArray_RejectsAUnionTypeWithoutTypes(t *testi } } func TestTypeSystem_UnionTypesMustBeArray_RejectsAUnionTypeWithEmptyTypes(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ Name: "SomeUnion", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Types: []*types.GraphQLObjectType{}, + Types: []*types.Object{}, })) expectedError := "Must provide Array of types for Union SomeUnion." if err == nil || err.Error() != expectedError { @@ -620,11 +620,11 @@ func TestTypeSystem_UnionTypesMustBeArray_RejectsAUnionTypeWithEmptyTypes(t *tes } func TestTypeSystem_InputObjectsMustHaveFields_AcceptsAnInputObjectTypeWithFields(t *testing.T) { - _, err := schemaWithInputObject(types.NewGraphQLInputObjectType(types.InputObjectConfig{ + _, err := schemaWithInputObject(types.NewInputObject(types.InputObjectConfig{ Name: "SomeInputObject", Fields: types.InputObjectConfigFieldMap{ "f": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, }, }, })) @@ -634,12 +634,12 @@ func TestTypeSystem_InputObjectsMustHaveFields_AcceptsAnInputObjectTypeWithField } func TestTypeSystem_InputObjectsMustHaveFields_AcceptsAnInputObjectTypeWithAFieldFunction(t *testing.T) { - _, err := schemaWithInputObject(types.NewGraphQLInputObjectType(types.InputObjectConfig{ + _, err := schemaWithInputObject(types.NewInputObject(types.InputObjectConfig{ Name: "SomeInputObject", Fields: (types.InputObjectConfigFieldMapThunk)(func() types.InputObjectConfigFieldMap { return types.InputObjectConfigFieldMap{ "f": &types.InputObjectFieldConfig{ - Type: types.GraphQLString, + Type: types.String, }, } }), @@ -650,7 +650,7 @@ func TestTypeSystem_InputObjectsMustHaveFields_AcceptsAnInputObjectTypeWithAFiel } func TestTypeSystem_InputObjectsMustHaveFields_RejectsAnInputObjectTypeWithMissingFields(t *testing.T) { - _, err := schemaWithInputObject(types.NewGraphQLInputObjectType(types.InputObjectConfig{ + _, err := schemaWithInputObject(types.NewInputObject(types.InputObjectConfig{ Name: "SomeInputObject", })) expectedError := "SomeInputObject fields must be an object with field names as keys or a function which return such an object." @@ -659,7 +659,7 @@ func TestTypeSystem_InputObjectsMustHaveFields_RejectsAnInputObjectTypeWithMissi } } func TestTypeSystem_InputObjectsMustHaveFields_RejectsAnInputObjectTypeWithEmptyFields(t *testing.T) { - _, err := schemaWithInputObject(types.NewGraphQLInputObjectType(types.InputObjectConfig{ + _, err := schemaWithInputObject(types.NewInputObject(types.InputObjectConfig{ Name: "SomeInputObject", Fields: types.InputObjectConfigFieldMap{}, })) @@ -670,14 +670,14 @@ func TestTypeSystem_InputObjectsMustHaveFields_RejectsAnInputObjectTypeWithEmpty } func TestTypeSystem_ObjectTypesMustBeAssertable_AcceptsAnObjectTypeWithAnIsTypeOfFunction(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { return true }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, })) @@ -688,23 +688,23 @@ func TestTypeSystem_ObjectTypesMustBeAssertable_AcceptsAnObjectTypeWithAnIsTypeO func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefiningResolveType(t *testing.T) { - anotherInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterfaceType}, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Interfaces: []*types.Interface{anotherInterfaceType}, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, })) @@ -714,23 +714,23 @@ func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefinin } func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceWithImplementingTypeDefiningIsTypeOf(t *testing.T) { - anotherInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterfaceType}, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + Interfaces: []*types.Interface{anotherInterfaceType}, + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { return true }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, })) @@ -741,26 +741,26 @@ func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceWithImpleme func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefiningResolveTypeWithImplementingTypeDefiningIsTypeOf(t *testing.T) { - anotherInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) - _, err := schemaWithFieldType(types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ Name: "SomeObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterfaceType}, - IsTypeOf: func(value interface{}, info types.GraphQLResolveInfo) bool { + Interfaces: []*types.Interface{anotherInterfaceType}, + IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { return true }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, })) @@ -771,10 +771,10 @@ func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefinin func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionTypeDefiningResolveType(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ Name: "SomeUnion", - Types: []*types.GraphQLObjectType{someObjectType}, - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + Types: []*types.Object{someObjectType}, + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, })) @@ -784,9 +784,9 @@ func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionTypeDefiningResolveT } func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionOfObjectTypesDefiningIsTypeOf(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ Name: "SomeUnion", - Types: []*types.GraphQLObjectType{objectWithIsTypeOf}, + Types: []*types.Object{objectWithIsTypeOf}, })) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -794,10 +794,10 @@ func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionOfObjectTypesDefinin } func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionTypeDefiningResolveTypeOfObjectTypesDefiningIsTypeOf(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ Name: "SomeUnion", - Types: []*types.GraphQLObjectType{objectWithIsTypeOf}, - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + Types: []*types.Object{objectWithIsTypeOf}, + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, })) @@ -807,9 +807,9 @@ func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionTypeDefiningResolveT } func TestTypeSystem_UnionTypesMustBeResolvable_RejectsAUnionTypeNotDefiningResolveTypeOfObjectTypesNotDefiningIsTypeOf(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLUnionType(types.GraphQLUnionTypeConfig{ + _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ Name: "SomeUnion", - Types: []*types.GraphQLObjectType{someObjectType}, + Types: []*types.Object{someObjectType}, })) expectedError := `Union Type SomeUnion does not provide a "resolveType" function and ` + `possible Type SomeObject does not provide a "isTypeOf" function. ` + @@ -821,7 +821,7 @@ func TestTypeSystem_UnionTypesMustBeResolvable_RejectsAUnionTypeNotDefiningResol func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningSerialize(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ + _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil @@ -833,7 +833,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningSeri } func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeNotDefiningSerialize(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ + _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ Name: "SomeScalar", })) expectedError := `SomeScalar must provide "serialize" function. If this custom Scalar ` + @@ -845,7 +845,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeNotDefiningS } func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningParseValueAndParseLiteral(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ + _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil @@ -863,7 +863,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningPars } func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeDefiningParseValueButNotParseLiteral(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ + _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil @@ -879,7 +879,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeDefiningPars } func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeDefiningParseLiteralButNotParseValue(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{ + _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil @@ -896,11 +896,11 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeDefiningPars func TestTypeSystem_EnumTypesMustBeWellDefined_AcceptsAWellDefinedEnumTypeWithEmptyValueDefinition(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ + _, err := schemaWithFieldType(types.NewEnum(types.EnumConfig{ Name: "SomeEnum", - Values: types.GraphQLEnumValueConfigMap{ - "FOO": &types.GraphQLEnumValueConfig{}, - "BAR": &types.GraphQLEnumValueConfig{}, + Values: types.EnumValueConfigMap{ + "FOO": &types.EnumValueConfig{}, + "BAR": &types.EnumValueConfig{}, }, })) if err != nil { @@ -909,13 +909,13 @@ func TestTypeSystem_EnumTypesMustBeWellDefined_AcceptsAWellDefinedEnumTypeWithEm } func TestTypeSystem_EnumTypesMustBeWellDefined_AcceptsAWellDefinedEnumTypeWithInternalValueDefinition(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ + _, err := schemaWithFieldType(types.NewEnum(types.EnumConfig{ Name: "SomeEnum", - Values: types.GraphQLEnumValueConfigMap{ - "FOO": &types.GraphQLEnumValueConfig{ + Values: types.EnumValueConfigMap{ + "FOO": &types.EnumValueConfig{ Value: 10, }, - "BAR": &types.GraphQLEnumValueConfig{ + "BAR": &types.EnumValueConfig{ Value: 20, }, }, @@ -926,7 +926,7 @@ func TestTypeSystem_EnumTypesMustBeWellDefined_AcceptsAWellDefinedEnumTypeWithIn } func TestTypeSystem_EnumTypesMustBeWellDefined_RejectsAnEnumTypeWithoutValues(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ + _, err := schemaWithFieldType(types.NewEnum(types.EnumConfig{ Name: "SomeEnum", })) expectedError := `SomeEnum values must be an object with value names as keys.` @@ -936,9 +936,9 @@ func TestTypeSystem_EnumTypesMustBeWellDefined_RejectsAnEnumTypeWithoutValues(t } func TestTypeSystem_EnumTypesMustBeWellDefined_RejectsAnEnumTypeWithEmptyValues(t *testing.T) { - _, err := schemaWithFieldType(types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{ + _, err := schemaWithFieldType(types.NewEnum(types.EnumConfig{ Name: "SomeEnum", - Values: types.GraphQLEnumValueConfigMap{}, + Values: types.EnumValueConfigMap{}, })) expectedError := `SomeEnum values must be an object with value names as keys.` if err == nil || err.Error() != expectedError { @@ -963,14 +963,14 @@ func TestTypeSystem_ObjectFieldsMustHaveOutputTypes_RejectsAnEmptyObjectFieldTyp } func TestTypeSystem_ObjectsCanOnlyImplementInterfaces_AcceptsAnObjectImplementingAnInterface(t *testing.T) { - anotherInterfaceType := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "f": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "f": &types.FieldConfig{ + Type: types.String, }, }, }) @@ -1050,8 +1050,8 @@ func TestTypeSystem_InputObjectFieldsMustHaveInputTypes_RejectsAnEmptyInputField } func TestTypeSystem_ListMustAcceptGraphQLTypes_AcceptsAnTypeAsItemTypeOfList(t *testing.T) { - testTypes := withModifiers([]types.GraphQLType{ - types.GraphQLString, + testTypes := withModifiers([]types.Type{ + types.String, someScalarType, someEnumType, someObjectType, @@ -1059,73 +1059,73 @@ func TestTypeSystem_ListMustAcceptGraphQLTypes_AcceptsAnTypeAsItemTypeOfList(t * someInterfaceType, }) for _, ttype := range testTypes { - result := types.NewGraphQLList(ttype) + result := types.NewList(ttype) if result.GetError() != nil { t.Fatalf(`unexpected error: %v for type "%v"`, result.GetError(), ttype) } } } func TestTypeSystem_ListMustAcceptGraphQLTypes_RejectsANilTypeAsItemTypeOfList(t *testing.T) { - result := types.NewGraphQLList(nil) - expectedError := `Can only create List of a GraphQLType but got: .` + result := types.NewList(nil) + expectedError := `Can only create List of a Type but got: .` if result.GetError() == nil || result.GetError().Error() != expectedError { t.Fatalf("Expected error: %v, got %v", expectedError, result.GetError()) } } func TestTypeSystem_NonNullMustAcceptGraphQLTypes_AcceptsAnTypeAsNullableTypeOfNonNull(t *testing.T) { - nullableTypes := []types.GraphQLType{ - types.GraphQLString, + nullableTypes := []types.Type{ + types.String, someScalarType, someObjectType, someUnionType, someInterfaceType, someEnumType, someInputObject, - types.NewGraphQLList(types.GraphQLString), - types.NewGraphQLList(types.NewGraphQLNonNull(types.GraphQLString)), + types.NewList(types.String), + types.NewList(types.NewNonNull(types.String)), } for _, ttype := range nullableTypes { - result := types.NewGraphQLNonNull(ttype) + result := types.NewNonNull(ttype) if result.GetError() != nil { t.Fatalf(`unexpected error: %v for type "%v"`, result.GetError(), ttype) } } } func TestTypeSystem_NonNullMustAcceptGraphQLTypes_RejectsNilAsNonNullableType(t *testing.T) { - result := types.NewGraphQLNonNull(nil) - expectedError := `Can only create NonNull of a Nullable GraphQLType but got: .` + result := types.NewNonNull(nil) + expectedError := `Can only create NonNull of a Nullable Type but got: .` if result.GetError() == nil || result.GetError().Error() != expectedError { t.Fatalf("Expected error: %v, got %v", expectedError, result.GetError()) } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWhichImplementsAnInterface(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, }, }) - anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + anotherObject := types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterface}, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Interfaces: []*types.Interface{anotherInterface}, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, @@ -1137,36 +1137,36 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWhi } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWhichImplementsAnInterfaceAlongWithMoreFields(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, }, }) - anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + anotherObject := types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterface}, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Interfaces: []*types.Interface{anotherInterface}, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, - "anotherfield": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + "anotherfield": &types.FieldConfig{ + Type: types.String, }, }, }) @@ -1176,34 +1176,34 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWhi } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWhichImplementsAnInterfaceFieldAlongWithMoreArguments(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, }, }) - anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + anotherObject := types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterface}, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Interfaces: []*types.Interface{anotherInterface}, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, - "anotherInput": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + "anotherInput": &types.ArgumentConfig{ + Type: types.String, }, }, }, @@ -1216,28 +1216,28 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWhi } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMissingAnInterfaceField(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, }, }) - anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + anotherObject := types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterface}, - Fields: types.GraphQLFieldConfigMap{ - "anotherfield": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Interfaces: []*types.Interface{anotherInterface}, + Fields: types.FieldConfigMap{ + "anotherfield": &types.FieldConfig{ + Type: types.String, }, }, }) @@ -1248,31 +1248,31 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMis } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithAnIncorrectlyTypedInterfaceField(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, }, }) - anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + anotherObject := types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterface}, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ + Interfaces: []*types.Interface{anotherInterface}, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ Type: someScalarType, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, @@ -1285,28 +1285,28 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWit } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMissingAnInterfaceArgument(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, }, }) - anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + anotherObject := types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterface}, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Interfaces: []*types.Interface{anotherInterface}, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, }, }, }) @@ -1317,30 +1317,30 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMis } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithAnIncorrectlyTypedInterfaceArgument(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ + Type: types.String, }, }, }, }, }) - anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + anotherObject := types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterface}, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, - Args: types.GraphQLFieldConfigArgumentMap{ - "input": &types.GraphQLArgumentConfig{ + Interfaces: []*types.Interface{anotherInterface}, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, + Args: types.FieldConfigArgument{ + "input": &types.ArgumentConfig{ Type: someScalarType, }, }, @@ -1354,23 +1354,23 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWit } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWithAnEquivalentlyModifiedInterfaceField(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLString)), + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.NewNonNull(types.NewList(types.String)), }, }, }) - anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + anotherObject := types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterface}, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(types.NewGraphQLList(types.GraphQLString)), + Interfaces: []*types.Interface{anotherInterface}, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.NewNonNull(types.NewList(types.String)), }, }, }) @@ -1380,23 +1380,23 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWit } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithADifferentlyModifiedInterfaceFieldType(t *testing.T) { - anotherInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{ + anotherInterface := types.NewInterface(types.InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType { + ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { return nil }, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.GraphQLString, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.String, }, }, }) - anotherObject := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{ + anotherObject := types.NewObject(types.ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.GraphQLInterfaceType{anotherInterface}, - Fields: types.GraphQLFieldConfigMap{ - "field": &types.GraphQLFieldConfig{ - Type: types.NewGraphQLNonNull(types.GraphQLString), + Interfaces: []*types.Interface{anotherInterface}, + Fields: types.FieldConfigMap{ + "field": &types.FieldConfig{ + Type: types.NewNonNull(types.String), }, }, }) diff --git a/validator/validator.go b/validator/validator.go index 0c1ee128..b9913452 100644 --- a/validator/validator.go +++ b/validator/validator.go @@ -8,10 +8,10 @@ import ( type ValidationResult struct { IsValid bool - Errors []graphqlerrors.GraphQLFormattedError + Errors []graphqlerrors.FormattedError } -func ValidateDocument(schema types.GraphQLSchema, ast *ast.Document) (vr ValidationResult) { +func ValidateDocument(schema types.Schema, ast *ast.Document) (vr ValidationResult) { vr.IsValid = true return vr } From 83bc4608a3be2e405250df485626194e0e075b06 Mon Sep 17 00:00:00 2001 From: Nathaniel Maman Date: Wed, 28 Oct 2015 02:33:17 +0200 Subject: [PATCH 4/6] move types and their dependencies to graphql --- executor/abstract_test.go => abstract_test.go | 307 +++---- ast_arguments.go | 33 + ast_definitions.go | 153 ++++ ast_directives.go | 33 + ast_document.go | 31 + ast_location.go | 18 + ast_name.go | 31 + ast_node.go | 45 + ast_selections.go | 131 +++ ast_type_definitions.go | 402 ++++++++ ast_types.go | 106 +++ ast_values.go | 305 +++++++ types/definition.go => definition.go | 117 ++- .../definition_test.go => definition_test.go | 325 ++++--- types/directives.go => directives.go | 12 +- .../directives_test.go => directives_test.go | 95 +- types/enum_type_test.go => enum_type_test.go | 152 ++- errors/graphql.go => error.go | 17 +- executor/executor.go => executor.go | 221 +++-- ..._schema_test.go => executor_schema_test.go | 109 ++- executor/executor_test.go => executor_test.go | 515 ++++++----- errors/formatted.go => formatted.go | 7 +- graphql.go | 29 +- graphql_test.go | 34 +- types/introspection.go => introspection.go | 51 +- ...pection_query.go => introspection_query.go | 2 +- ...ospection_test.go => introspection_test.go | 233 +++-- kinds/kinds.go | 38 + ...tchen-sink.graphql => kitchen-sink.graphql | 0 language/ast/arguments.go | 33 - language/ast/definitions.go | 153 ---- language/ast/directives.go | 33 - language/ast/document.go | 31 - language/ast/location.go | 22 - language/ast/name.go | 29 - language/ast/node.go | 45 - language/ast/selections.go | 131 --- language/ast/type_definitions.go | 402 -------- language/ast/types.go | 106 --- language/ast/values.go | 305 ------- language/kinds/kinds.go | 38 - language/parser/schema_parser_test.go | 759 --------------- language/lexer/lexer.go => lexer.go | 29 +- language/lexer/lexer_test.go => lexer_test.go | 12 +- executor/lists_test.go => lists_test.go | 223 +++-- errors/located.go => located.go | 12 +- language/location/location.go => location.go | 6 +- .../mutations_test.go => mutations_test.go | 105 +-- executor/nonnull_test.go => nonnull_test.go | 544 ++++++----- language/parser/parser.go => parser.go | 373 ++++---- .../parser/parser_test.go => parser_test.go | 128 ++- language/printer/printer.go => printer.go | 208 +++-- .../printer_test.go => printer_test.go | 38 +- types/scalars.go => scalars.go | 28 +- ...n_test.go => scalars_serialization_test.go | 2 +- ...ink.graphql => schema-kitchen-sink.graphql | 0 types/schema.go => schema.go | 2 +- schema_parser_test.go | 754 +++++++++++++++ ..._printer_test.go => schema_printer_test.go | 49 +- errors/sortutil.go => sortutil.go | 2 +- language/source/source.go => source.go | 2 +- errors/syntax.go => syntax.go | 14 +- testutil/testutil.go => testutil.go | 168 ++-- testutil/testutil_test.go => testutil_test.go | 27 +- types.go | 12 + types/types.go | 16 - ...terface_test.go => union_interface_test.go | 187 ++-- .../validation_test.go => validation_test.go | 863 +++++++++--------- validator.go | 11 + validator/validator.go | 17 - executor/values.go => values.go | 101 +- .../variables_test.go => variables_test.go | 624 +++++++------ language/visitor/visitor.go => visitor.go | 8 +- .../visitor_test.go => visitor_test.go | 186 ++-- 74 files changed, 5115 insertions(+), 5275 deletions(-) rename executor/abstract_test.go => abstract_test.go (54%) create mode 100644 ast_arguments.go create mode 100644 ast_definitions.go create mode 100644 ast_directives.go create mode 100644 ast_document.go create mode 100644 ast_location.go create mode 100644 ast_name.go create mode 100644 ast_node.go create mode 100644 ast_selections.go create mode 100644 ast_type_definitions.go create mode 100644 ast_types.go create mode 100644 ast_values.go rename types/definition.go => definition.go (90%) rename types/definition_test.go => definition_test.go (54%) rename types/directives.go => directives.go (84%) rename executor/directives_test.go => directives_test.go (77%) rename types/enum_type_test.go => enum_type_test.go (64%) rename errors/graphql.go => error.go (65%) rename executor/executor.go => executor.go (76%) rename executor/executor_schema_test.go => executor_schema_test.go (71%) rename executor/executor_test.go => executor_test.go (59%) rename errors/formatted.go => formatted.go (84%) rename types/introspection.go => introspection.go (91%) rename testutil/introspection_query.go => introspection_query.go (98%) rename types/introspection_test.go => introspection_test.go (84%) create mode 100644 kinds/kinds.go rename language/parser/kitchen-sink.graphql => kitchen-sink.graphql (100%) delete mode 100644 language/ast/arguments.go delete mode 100644 language/ast/definitions.go delete mode 100644 language/ast/directives.go delete mode 100644 language/ast/document.go delete mode 100644 language/ast/location.go delete mode 100644 language/ast/name.go delete mode 100644 language/ast/node.go delete mode 100644 language/ast/selections.go delete mode 100644 language/ast/type_definitions.go delete mode 100644 language/ast/types.go delete mode 100644 language/ast/values.go delete mode 100644 language/kinds/kinds.go delete mode 100644 language/parser/schema_parser_test.go rename language/lexer/lexer.go => lexer.go (91%) rename language/lexer/lexer_test.go => lexer_test.go (97%) rename executor/lists_test.go => lists_test.go (74%) rename errors/located.go => located.go (59%) rename language/location/location.go => location.go (80%) rename executor/mutations_test.go => mutations_test.go (65%) rename executor/nonnull_test.go => nonnull_test.go (56%) rename language/parser/parser.go => parser.go (64%) rename language/parser/parser_test.go => parser_test.go (78%) rename language/printer/printer.go => printer.go (56%) rename language/printer/printer_test.go => printer_test.go (56%) rename types/scalars.go => scalars.go (85%) rename types/scalars_serialization_test.go => scalars_serialization_test.go (99%) rename language/parser/schema-kitchen-sink.graphql => schema-kitchen-sink.graphql (100%) rename types/schema.go => schema.go (99%) create mode 100644 schema_parser_test.go rename language/printer/schema_printer_test.go => schema_printer_test.go (56%) rename errors/sortutil.go => sortutil.go (97%) rename language/source/source.go => source.go (92%) rename errors/syntax.go => syntax.go (71%) rename testutil/testutil.go => testutil.go (69%) rename testutil/testutil_test.go => testutil_test.go (88%) create mode 100644 types.go delete mode 100644 types/types.go rename executor/union_interface_test.go => union_interface_test.go (67%) rename types/validation_test.go => validation_test.go (56%) create mode 100644 validator.go delete mode 100644 validator/validator.go rename executor/values.go => values.go (74%) rename executor/variables_test.go => variables_test.go (63%) rename language/visitor/visitor.go => visitor.go (98%) rename language/visitor/visitor_test.go => visitor_test.go (73%) diff --git a/executor/abstract_test.go b/abstract_test.go similarity index 54% rename from executor/abstract_test.go rename to abstract_test.go index 26935583..7353afdc 100644 --- a/executor/abstract_test.go +++ b/abstract_test.go @@ -1,11 +1,6 @@ -package executor_test +package graphql import ( - "github.com/chris-ramon/graphql" - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) @@ -26,38 +21,38 @@ type testHuman struct { func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { - petType := types.NewInterface(types.InterfaceConfig{ + petType := NewInterface(InterfaceConfig{ Name: "Pet", - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, }, }, }) // ie declare that Dog belongs to Pet interface - _ = types.NewObject(types.ObjectConfig{ + _ = NewObject(ObjectConfig{ Name: "Dog", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ petType, }, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testDog) return ok }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Name } return nil }, }, - "woofs": &types.FieldConfig{ - Type: types.Boolean, - Resolve: func(p types.GQLFRParams) interface{} { + "woofs": &FieldConfig{ + Type: Boolean, + Resolve: func(p GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Woofs } @@ -67,28 +62,28 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { }, }) // ie declare that Cat belongs to Pet interface - _ = types.NewObject(types.ObjectConfig{ + _ = NewObject(ObjectConfig{ Name: "Cat", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ petType, }, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testCat) return ok }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Name } return nil }, }, - "meows": &types.FieldConfig{ - Type: types.Boolean, - Resolve: func(p types.GQLFRParams) interface{} { + "meows": &FieldConfig{ + Type: Boolean, + Resolve: func(p GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Meows } @@ -97,13 +92,13 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "pets": &types.FieldConfig{ - Type: types.NewList(petType), - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "pets": &FieldConfig{ + Type: NewList(petType), + Resolve: func(p GQLFRParams) interface{} { return []interface{}{ &testDog{"Odie", true}, &testCat{"Garfield", false}, @@ -129,7 +124,7 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { } }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "pets": []interface{}{ map[string]interface{}{ @@ -145,9 +140,9 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { Errors: nil, } - resultChannel := make(chan *types.Result) + resultChannel := make(chan *Result) - go graphql.Graphql(graphql.Params{ + go Graphql(Params{ Schema: schema, RequestString: query, }, resultChannel) @@ -156,31 +151,31 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForInterface(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { - dogType := types.NewObject(types.ObjectConfig{ + dogType := NewObject(ObjectConfig{ Name: "Dog", - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testDog) return ok }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Name } return nil }, }, - "woofs": &types.FieldConfig{ - Type: types.Boolean, - Resolve: func(p types.GQLFRParams) interface{} { + "woofs": &FieldConfig{ + Type: Boolean, + Resolve: func(p GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Woofs } @@ -189,25 +184,25 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { }, }, }) - catType := types.NewObject(types.ObjectConfig{ + catType := NewObject(ObjectConfig{ Name: "Cat", - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testCat) return ok }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Name } return nil }, }, - "meows": &types.FieldConfig{ - Type: types.Boolean, - Resolve: func(p types.GQLFRParams) interface{} { + "meows": &FieldConfig{ + Type: Boolean, + Resolve: func(p GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Meows } @@ -217,12 +212,12 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { }, }) // ie declare Pet has Dot and Cat object types - petType := types.NewUnion(types.UnionConfig{ + petType := NewUnion(UnionConfig{ Name: "Pet", - Types: []*types.Object{ + Types: []*Object{ dogType, catType, }, - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { if _, ok := value.(*testCat); ok { return catType } @@ -232,13 +227,13 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { return nil }, }) - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "pets": &types.FieldConfig{ - Type: types.NewList(petType), - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "pets": &FieldConfig{ + Type: NewList(petType), + Resolve: func(p GQLFRParams) interface{} { return []interface{}{ &testDog{"Odie", true}, &testCat{"Garfield", false}, @@ -264,7 +259,7 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { } }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "pets": []interface{}{ map[string]interface{}{ @@ -280,9 +275,9 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { Errors: nil, } - resultChannel := make(chan *types.Result) + resultChannel := make(chan *Result) - go graphql.Graphql(graphql.Params{ + go Graphql(Params{ Schema: schema, RequestString: query, }, resultChannel) @@ -292,23 +287,23 @@ func TestIsTypeOfUsedToResolveRuntimeTypeForUnion(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { - var dogType *types.Object - var catType *types.Object - var humanType *types.Object - petType := types.NewInterface(types.InterfaceConfig{ + var dogType *Object + var catType *Object + var humanType *Object + petType := NewInterface(InterfaceConfig{ Name: "Pet", - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, }, }, - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { if _, ok := value.(*testCat); ok { return catType } @@ -322,12 +317,12 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { }, }) - humanType = types.NewObject(types.ObjectConfig{ + humanType = NewObject(ObjectConfig{ Name: "Human", - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if human, ok := p.Source.(*testHuman); ok { return human.Name } @@ -336,28 +331,28 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { }, }, }) - dogType = types.NewObject(types.ObjectConfig{ + dogType = NewObject(ObjectConfig{ Name: "Dog", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ petType, }, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testDog) return ok }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Name } return nil }, }, - "woofs": &types.FieldConfig{ - Type: types.Boolean, - Resolve: func(p types.GQLFRParams) interface{} { + "woofs": &FieldConfig{ + Type: Boolean, + Resolve: func(p GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Woofs } @@ -366,28 +361,28 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { }, }, }) - catType = types.NewObject(types.ObjectConfig{ + catType = NewObject(ObjectConfig{ Name: "Cat", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ petType, }, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testCat) return ok }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Name } return nil }, }, - "meows": &types.FieldConfig{ - Type: types.Boolean, - Resolve: func(p types.GQLFRParams) interface{} { + "meows": &FieldConfig{ + Type: Boolean, + Resolve: func(p GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Meows } @@ -396,13 +391,13 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "pets": &types.FieldConfig{ - Type: types.NewList(petType), - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "pets": &FieldConfig{ + Type: NewList(petType), + Resolve: func(p GQLFRParams) interface{} { return []interface{}{ &testDog{"Odie", true}, &testCat{"Garfield", false}, @@ -429,7 +424,7 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { } }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "pets": []interface{}{ map[string]interface{}{ @@ -443,17 +438,17 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { nil, }, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Runtime Object type "Human" is not a possible type for "Pet".`, - Locations: []location.SourceLocation{}, + Locations: []SourceLocation{}, }, }, } - resultChannel := make(chan *types.Result) + resultChannel := make(chan *Result) - go graphql.Graphql(graphql.Params{ + go Graphql(Params{ Schema: schema, RequestString: query, }, resultChannel) @@ -462,18 +457,18 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { t.Fatalf("wrong result, expected errors: %v, got: %v", len(expected.Errors), len(result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { - humanType := types.NewObject(types.ObjectConfig{ + humanType := NewObject(ObjectConfig{ Name: "Human", - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if human, ok := p.Source.(*testHuman); ok { return human.Name } @@ -482,25 +477,25 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { }, }, }) - dogType := types.NewObject(types.ObjectConfig{ + dogType := NewObject(ObjectConfig{ Name: "Dog", - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testDog) return ok }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Name } return nil }, }, - "woofs": &types.FieldConfig{ - Type: types.Boolean, - Resolve: func(p types.GQLFRParams) interface{} { + "woofs": &FieldConfig{ + Type: Boolean, + Resolve: func(p GQLFRParams) interface{} { if dog, ok := p.Source.(*testDog); ok { return dog.Woofs } @@ -509,25 +504,25 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { }, }, }) - catType := types.NewObject(types.ObjectConfig{ + catType := NewObject(ObjectConfig{ Name: "Cat", - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testCat) return ok }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Name } return nil }, }, - "meows": &types.FieldConfig{ - Type: types.Boolean, - Resolve: func(p types.GQLFRParams) interface{} { + "meows": &FieldConfig{ + Type: Boolean, + Resolve: func(p GQLFRParams) interface{} { if cat, ok := p.Source.(*testCat); ok { return cat.Meows } @@ -536,12 +531,12 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { }, }, }) - petType := types.NewUnion(types.UnionConfig{ + petType := NewUnion(UnionConfig{ Name: "Pet", - Types: []*types.Object{ + Types: []*Object{ dogType, catType, }, - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { if _, ok := value.(*testCat); ok { return catType } @@ -554,13 +549,13 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { return nil }, }) - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "pets": &types.FieldConfig{ - Type: types.NewList(petType), - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "pets": &FieldConfig{ + Type: NewList(petType), + Resolve: func(p GQLFRParams) interface{} { return []interface{}{ &testDog{"Odie", true}, &testCat{"Garfield", false}, @@ -587,7 +582,7 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { } }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "pets": []interface{}{ map[string]interface{}{ @@ -601,17 +596,17 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { nil, }, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Runtime Object type "Human" is not a possible type for "Pet".`, - Locations: []location.SourceLocation{}, + Locations: []SourceLocation{}, }, }, } - resultChannel := make(chan *types.Result) + resultChannel := make(chan *Result) - go graphql.Graphql(graphql.Params{ + go Graphql(Params{ Schema: schema, RequestString: query, }, resultChannel) @@ -620,6 +615,6 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { t.Fatalf("wrong result, expected errors: %v, got: %v", len(expected.Errors), len(result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/ast_arguments.go b/ast_arguments.go new file mode 100644 index 00000000..1a245df0 --- /dev/null +++ b/ast_arguments.go @@ -0,0 +1,33 @@ +package graphql + +import ( + "github.com/chris-ramon/graphql/kinds" +) + +// Argument implements Node +type AstArgument struct { + Kind string + Loc *AstLocation + Name *AstName + Value Value +} + +func NewAstArgument(arg *AstArgument) *AstArgument { + if arg == nil { + arg = &AstArgument{} + } + return &AstArgument{ + Kind: kinds.Argument, + Loc: arg.Loc, + Name: arg.Name, + Value: arg.Value, + } +} + +func (arg *AstArgument) GetKind() string { + return arg.Kind +} + +func (arg *AstArgument) GetLoc() *AstLocation { + return arg.Loc +} diff --git a/ast_definitions.go b/ast_definitions.go new file mode 100644 index 00000000..631e6364 --- /dev/null +++ b/ast_definitions.go @@ -0,0 +1,153 @@ +package graphql + +import ( + "github.com/chris-ramon/graphql/kinds" +) + +type Definition interface { + // TODO: determine the minimal set of interface for `Definition` + GetOperation() string + GetVariableDefinitions() []*AstVariableDefinition + GetSelectionSet() *AstSelectionSet +} + +// Ensure that all definition types implements Definition interface +var _ Definition = (*AstOperationDefinition)(nil) +var _ Definition = (*AstFragmentDefinition)(nil) +var _ Definition = (Definition)(nil) + +// AstOperationDefinition implements Node, Definition +type AstOperationDefinition struct { + Kind string + Loc *AstLocation + Operation string + Name *AstName + VariableDefinitions []*AstVariableDefinition + Directives []*AstDirective + SelectionSet *AstSelectionSet +} + +func NewAstOperationDefinition(op *AstOperationDefinition) *AstOperationDefinition { + if op == nil { + op = &AstOperationDefinition{} + } + return &AstOperationDefinition{ + Kind: kinds.OperationDefinition, + Loc: op.Loc, + Operation: op.Operation, + Name: op.Name, + VariableDefinitions: op.VariableDefinitions, + Directives: op.Directives, + SelectionSet: op.SelectionSet, + } +} + +func (op *AstOperationDefinition) GetKind() string { + return op.Kind +} + +func (op *AstOperationDefinition) GetLoc() *AstLocation { + return op.Loc +} + +func (op *AstOperationDefinition) GetOperation() string { + return op.Operation +} + +func (op *AstOperationDefinition) GetName() *AstName { + return op.Name +} + +func (op *AstOperationDefinition) GetVariableDefinitions() []*AstVariableDefinition { + return op.VariableDefinitions +} + +func (op *AstOperationDefinition) GetDirectives() []*AstDirective { + return op.Directives +} + +func (op *AstOperationDefinition) GetSelectionSet() *AstSelectionSet { + return op.SelectionSet +} + +// AstFragmentDefinition implements Node, Definition +type AstFragmentDefinition struct { + Kind string + Loc *AstLocation + Operation string + Name *AstName + VariableDefinitions []*AstVariableDefinition + TypeCondition *AstNamed + Directives []*AstDirective + SelectionSet *AstSelectionSet +} + +func NewAstFragmentDefinition(fd *AstFragmentDefinition) *AstFragmentDefinition { + if fd == nil { + fd = &AstFragmentDefinition{} + } + return &AstFragmentDefinition{ + Kind: kinds.FragmentDefinition, + Loc: fd.Loc, + Operation: fd.Operation, + Name: fd.Name, + VariableDefinitions: fd.VariableDefinitions, + TypeCondition: fd.TypeCondition, + Directives: fd.Directives, + SelectionSet: fd.SelectionSet, + } +} + +func (fd *AstFragmentDefinition) GetKind() string { + return fd.Kind +} + +func (fd *AstFragmentDefinition) GetLoc() *AstLocation { + return fd.Loc +} + +func (fd *AstFragmentDefinition) GetOperation() string { + return fd.Operation +} + +func (fd *AstFragmentDefinition) GetName() *AstName { + return fd.Name +} + +func (fd *AstFragmentDefinition) GetVariableDefinitions() []*AstVariableDefinition { + return fd.VariableDefinitions +} + +func (fd *AstFragmentDefinition) GetSelectionSet() *AstSelectionSet { + return fd.SelectionSet +} + +// AstVariableDefinition implements Node +type AstVariableDefinition struct { + Kind string + Loc *AstLocation + Variable *AstVariable + Type AstType + DefaultValue Value +} + +func NewAstVariableDefinition(vd *AstVariableDefinition) *AstVariableDefinition { + if vd == nil { + vd = &AstVariableDefinition{} + } + return &AstVariableDefinition{ + Kind: kinds.VariableDefinition, + Loc: vd.Loc, + Variable: vd.Variable, + Type: vd.Type, + DefaultValue: vd.DefaultValue, + } +} + +func (vd *AstVariableDefinition) GetKind() string { + return vd.Kind +} + +func (vd *AstVariableDefinition) GetLoc() *AstLocation { + return vd.Loc +} diff --git a/ast_directives.go b/ast_directives.go new file mode 100644 index 00000000..e9451154 --- /dev/null +++ b/ast_directives.go @@ -0,0 +1,33 @@ +package graphql + +import ( + "github.com/chris-ramon/graphql/kinds" +) + +// Directive implements Node +type AstDirective struct { + Kind string + Loc *AstLocation + Name *AstName + Arguments []*AstArgument +} + +func NewAstDirective(dir *AstDirective) *AstDirective { + if dir == nil { + dir = &AstDirective{} + } + return &AstDirective{ + Kind: kinds.Directive, + Loc: dir.Loc, + Name: dir.Name, + Arguments: dir.Arguments, + } +} + +func (dir *AstDirective) GetKind() string { + return dir.Kind +} + +func (dir *AstDirective) GetLoc() *AstLocation { + return dir.Loc +} diff --git a/ast_document.go b/ast_document.go new file mode 100644 index 00000000..a7ca2148 --- /dev/null +++ b/ast_document.go @@ -0,0 +1,31 @@ +package graphql + +import ( + "github.com/chris-ramon/graphql/kinds" +) + +// Document implements Node +type AstDocument struct { + Kind string + Loc *AstLocation + Definitions []Node +} + +func NewAstDocument(d *AstDocument) *AstDocument { + if d == nil { + d = &AstDocument{} + } + return &AstDocument{ + Kind: kinds.Document, + Loc: d.Loc, + Definitions: d.Definitions, + } +} + +func (node *AstDocument) GetKind() string { + return node.Kind +} + +func (node *AstDocument) GetLoc() *AstLocation { + return node.Loc +} diff --git a/ast_location.go b/ast_location.go new file mode 100644 index 00000000..aed1ddbf --- /dev/null +++ b/ast_location.go @@ -0,0 +1,18 @@ +package graphql + +type AstLocation struct { + Start int + End int + Source *Source +} + +func NewAstLocation(loc *AstLocation) *AstLocation { + if loc == nil { + loc = &AstLocation{} + } + return &AstLocation{ + Start: loc.Start, + End: loc.End, + Source: loc.Source, + } +} diff --git a/ast_name.go b/ast_name.go new file mode 100644 index 00000000..55f81fc6 --- /dev/null +++ b/ast_name.go @@ -0,0 +1,31 @@ +package graphql + +import ( + "github.com/chris-ramon/graphql/kinds" +) + +// AstName implements Node +type AstName struct { + Kind string + Loc *AstLocation + Value string +} + +func NewAstName(node *AstName) *AstName { + if node == nil { + node = &AstName{} + } + return &AstName{ + Kind: kinds.Name, + Value: node.Value, + Loc: node.Loc, + } +} + +func (node *AstName) GetKind() string { + return node.Kind +} + +func (node *AstName) GetLoc() *AstLocation { + return node.Loc +} diff --git a/ast_node.go b/ast_node.go new file mode 100644 index 00000000..af8e395e --- /dev/null +++ b/ast_node.go @@ -0,0 +1,45 @@ +package graphql + +type Node interface { + GetKind() string + GetLoc() *AstLocation +} + +// The list of all possible AST node graphql. +// Ensure that all node types implements Node interface +var _ Node = (*AstName)(nil) +var _ Node = (*AstDocument)(nil) +var _ Node = (*AstOperationDefinition)(nil) +var _ Node = (*AstVariableDefinition)(nil) +var _ Node = (*AstVariable)(nil) +var _ Node = (*AstSelectionSet)(nil) +var _ Node = (*AstField)(nil) +var _ Node = (*AstArgument)(nil) +var _ Node = (*AstFragmentSpread)(nil) +var _ Node = (*AstInlineFragment)(nil) +var _ Node = (*AstFragmentDefinition)(nil) +var _ Node = (*AstIntValue)(nil) +var _ Node = (*AstFloatValue)(nil) +var _ Node = (*AstStringValue)(nil) +var _ Node = (*AstBooleanValue)(nil) +var _ Node = (*AstEnumValue)(nil) +var _ Node = (*AstListValue)(nil) +var _ Node = (*AstObjectValue)(nil) +var _ Node = (*AstObjectField)(nil) +var _ Node = (*AstDirective)(nil) +var _ Node = (*AstList)(nil) +var _ Node = (*AstNonNull)(nil) +var _ Node = (*AstObjectDefinition)(nil) +var _ Node = (*AstFieldDefinition)(nil) +var _ Node = (*AstInputValueDefinition)(nil) +var _ Node = (*AstInterfaceDefinition)(nil) +var _ Node = (*AstUnionDefinition)(nil) +var _ Node = (*AstScalarDefinition)(nil) +var _ Node = (*AstEnumDefinition)(nil) +var _ Node = (*AstEnumValueDefinition)(nil) +var _ Node = (*AstInputObjectDefinition)(nil) +var _ Node = (*AstTypeExtensionDefinition)(nil) + +// TODO: File issue in `graphql-js` where AstNamed is not +// defined as a Node. This might be a mistake in `graphql-js`? +var _ Node = (*AstNamed)(nil) diff --git a/ast_selections.go b/ast_selections.go new file mode 100644 index 00000000..c3c8fd44 --- /dev/null +++ b/ast_selections.go @@ -0,0 +1,131 @@ +package graphql + +import ( + "github.com/chris-ramon/graphql/kinds" +) + +type Selection interface { +} + +// Ensure that all definition types implements Selection interface +var _ Selection = (*AstField)(nil) +var _ Selection = (*AstFragmentSpread)(nil) +var _ Selection = (*AstInlineFragment)(nil) + +// AstField implements Node, Selection +type AstField struct { + Kind string + Loc *AstLocation + Alias *AstName + Name *AstName + Arguments []*AstArgument + Directives []*AstDirective + SelectionSet *AstSelectionSet +} + +func NewField(f *AstField) *AstField { + if f == nil { + f = &AstField{} + } + return &AstField{ + Kind: kinds.Field, + Loc: f.Loc, + Alias: f.Alias, + Name: f.Name, + Arguments: f.Arguments, + Directives: f.Directives, + SelectionSet: f.SelectionSet, + } +} + +func (f *AstField) GetKind() string { + return f.Kind +} + +func (f *AstField) GetLoc() *AstLocation { + return f.Loc +} + +// FragmentSpread implements Node, Selection +type AstFragmentSpread struct { + Kind string + Loc *AstLocation + Name *AstName + Directives []*AstDirective +} + +func NewAstFragmentSpread(fs *AstFragmentSpread) *AstFragmentSpread { + if fs == nil { + fs = &AstFragmentSpread{} + } + return &AstFragmentSpread{ + Kind: kinds.FragmentSpread, + Loc: fs.Loc, + Name: fs.Name, + Directives: fs.Directives, + } +} + +func (fs *AstFragmentSpread) GetKind() string { + return fs.Kind +} + +func (fs *AstFragmentSpread) GetLoc() *AstLocation { + return fs.Loc +} + +// InlineFragment implements Node, Selection +type AstInlineFragment struct { + Kind string + Loc *AstLocation + TypeCondition *AstNamed + Directives []*AstDirective + SelectionSet *AstSelectionSet +} + +func NewAstInlineFragment(f *AstInlineFragment) *AstInlineFragment { + if f == nil { + f = &AstInlineFragment{} + } + return &AstInlineFragment{ + Kind: kinds.InlineFragment, + Loc: f.Loc, + TypeCondition: f.TypeCondition, + Directives: f.Directives, + SelectionSet: f.SelectionSet, + } +} + +func (f *AstInlineFragment) GetKind() string { + return f.Kind +} + +func (f *AstInlineFragment) GetLoc() *AstLocation { + return f.Loc +} + +// AstSelectionSet implements Node +type AstSelectionSet struct { + Kind string + Loc *AstLocation + Selections []Selection +} + +func NewAstSelectionSet(ss *AstSelectionSet) *AstSelectionSet { + if ss == nil { + ss = &AstSelectionSet{} + } + return &AstSelectionSet{ + Kind: kinds.SelectionSet, + Loc: ss.Loc, + Selections: ss.Selections, + } +} + +func (ss *AstSelectionSet) GetKind() string { + return ss.Kind +} + +func (ss *AstSelectionSet) GetLoc() *AstLocation { + return ss.Loc +} diff --git a/ast_type_definitions.go b/ast_type_definitions.go new file mode 100644 index 00000000..2978e78b --- /dev/null +++ b/ast_type_definitions.go @@ -0,0 +1,402 @@ +package graphql + +import ( + "github.com/chris-ramon/graphql/kinds" +) + +// Ensure that all typeDefinition types implements Definition interface +var _ Definition = (*AstObjectDefinition)(nil) +var _ Definition = (*AstInterfaceDefinition)(nil) +var _ Definition = (*AstUnionDefinition)(nil) +var _ Definition = (*AstScalarDefinition)(nil) +var _ Definition = (*AstEnumDefinition)(nil) +var _ Definition = (*AstInputObjectDefinition)(nil) +var _ Definition = (*AstTypeExtensionDefinition)(nil) + +// AstObjectDefinition implements Node, Definition +type AstObjectDefinition struct { + Kind string + Loc *AstLocation + Name *AstName + Interfaces []*AstNamed + Fields []*AstFieldDefinition +} + +func NewAstObjectDefinition(def *AstObjectDefinition) *AstObjectDefinition { + if def == nil { + def = &AstObjectDefinition{} + } + return &AstObjectDefinition{ + Kind: kinds.ObjectDefinition, + Loc: def.Loc, + Name: def.Name, + Interfaces: def.Interfaces, + Fields: def.Fields, + } +} + +func (def *AstObjectDefinition) GetKind() string { + return def.Kind +} + +func (def *AstObjectDefinition) GetLoc() *AstLocation { + return def.Loc +} + +func (def *AstObjectDefinition) GetName() *AstName { + return def.Name +} + +func (def *AstObjectDefinition) GetVariableDefinitions() []*AstVariableDefinition { + return []*AstVariableDefinition{} +} + +func (def *AstObjectDefinition) GetSelectionSet() *AstSelectionSet { + return &AstSelectionSet{} +} + +func (def *AstObjectDefinition) GetOperation() string { + return "" +} + +// AstFieldDefinition implements Node +type AstFieldDefinition struct { + Kind string + Loc *AstLocation + Name *AstName + Arguments []*AstInputValueDefinition + Type AstType +} + +func NewAstFieldDefinition(def *AstFieldDefinition) *AstFieldDefinition { + if def == nil { + def = &AstFieldDefinition{} + } + return &AstFieldDefinition{ + Kind: kinds.FieldDefinition, + Loc: def.Loc, + Name: def.Name, + Arguments: def.Arguments, + Type: def.Type, + } +} + +func (def *AstFieldDefinition) GetKind() string { + return def.Kind +} + +func (def *AstFieldDefinition) GetLoc() *AstLocation { + return def.Loc +} + +// AstInputValueDefinition implements Node +type AstInputValueDefinition struct { + Kind string + Loc *AstLocation + Name *AstName + Type AstType + DefaultValue Value +} + +func NewAstInputValueDefinition(def *AstInputValueDefinition) *AstInputValueDefinition { + if def == nil { + def = &AstInputValueDefinition{} + } + return &AstInputValueDefinition{ + Kind: kinds.InputValueDefinition, + Loc: def.Loc, + Name: def.Name, + Type: def.Type, + DefaultValue: def.DefaultValue, + } +} + +func (def *AstInputValueDefinition) GetKind() string { + return def.Kind +} + +func (def *AstInputValueDefinition) GetLoc() *AstLocation { + return def.Loc +} + +// AstInterfaceDefinition implements Node, Definition +type AstInterfaceDefinition struct { + Kind string + Loc *AstLocation + Name *AstName + Fields []*AstFieldDefinition +} + +func NewAstInterfaceDefinition(def *AstInterfaceDefinition) *AstInterfaceDefinition { + if def == nil { + def = &AstInterfaceDefinition{} + } + return &AstInterfaceDefinition{ + Kind: kinds.InterfaceDefinition, + Loc: def.Loc, + Name: def.Name, + Fields: def.Fields, + } +} + +func (def *AstInterfaceDefinition) GetKind() string { + return def.Kind +} + +func (def *AstInterfaceDefinition) GetLoc() *AstLocation { + return def.Loc +} + +func (def *AstInterfaceDefinition) GetName() *AstName { + return def.Name +} + +func (def *AstInterfaceDefinition) GetVariableDefinitions() []*AstVariableDefinition { + return []*AstVariableDefinition{} +} + +func (def *AstInterfaceDefinition) GetSelectionSet() *AstSelectionSet { + return &AstSelectionSet{} +} + +func (def *AstInterfaceDefinition) GetOperation() string { + return "" +} + +// AstUnionDefinition implements Node, Definition +type AstUnionDefinition struct { + Kind string + Loc *AstLocation + Name *AstName + Types []*AstNamed +} + +func NewAstUnionDefinition(def *AstUnionDefinition) *AstUnionDefinition { + if def == nil { + def = &AstUnionDefinition{} + } + return &AstUnionDefinition{ + Kind: kinds.UnionDefinition, + Loc: def.Loc, + Name: def.Name, + Types: def.Types, + } +} + +func (def *AstUnionDefinition) GetKind() string { + return def.Kind +} + +func (def *AstUnionDefinition) GetLoc() *AstLocation { + return def.Loc +} + +func (def *AstUnionDefinition) GetName() *AstName { + return def.Name +} + +func (def *AstUnionDefinition) GetVariableDefinitions() []*AstVariableDefinition { + return []*AstVariableDefinition{} +} + +func (def *AstUnionDefinition) GetSelectionSet() *AstSelectionSet { + return &AstSelectionSet{} +} + +func (def *AstUnionDefinition) GetOperation() string { + return "" +} + +// AstScalarDefinition implements Node, Definition +type AstScalarDefinition struct { + Kind string + Loc *AstLocation + Name *AstName +} + +func NewAstScalarDefinition(def *AstScalarDefinition) *AstScalarDefinition { + if def == nil { + def = &AstScalarDefinition{} + } + return &AstScalarDefinition{ + Kind: kinds.ScalarDefinition, + Loc: def.Loc, + Name: def.Name, + } +} + +func (def *AstScalarDefinition) GetKind() string { + return def.Kind +} + +func (def *AstScalarDefinition) GetLoc() *AstLocation { + return def.Loc +} + +func (def *AstScalarDefinition) GetName() *AstName { + return def.Name +} + +func (def *AstScalarDefinition) GetVariableDefinitions() []*AstVariableDefinition { + return []*AstVariableDefinition{} +} + +func (def *AstScalarDefinition) GetSelectionSet() *AstSelectionSet { + return &AstSelectionSet{} +} + +func (def *AstScalarDefinition) GetOperation() string { + return "" +} + +// AstEnumDefinition implements Node, Definition +type AstEnumDefinition struct { + Kind string + Loc *AstLocation + Name *AstName + Values []*AstEnumValueDefinition +} + +func NewAstEnumDefinition(def *AstEnumDefinition) *AstEnumDefinition { + if def == nil { + def = &AstEnumDefinition{} + } + return &AstEnumDefinition{ + Kind: kinds.EnumDefinition, + Loc: def.Loc, + Name: def.Name, + Values: def.Values, + } +} + +func (def *AstEnumDefinition) GetKind() string { + return def.Kind +} + +func (def *AstEnumDefinition) GetLoc() *AstLocation { + return def.Loc +} + +func (def *AstEnumDefinition) GetName() *AstName { + return def.Name +} + +func (def *AstEnumDefinition) GetVariableDefinitions() []*AstVariableDefinition { + return []*AstVariableDefinition{} +} + +func (def *AstEnumDefinition) GetSelectionSet() *AstSelectionSet { + return &AstSelectionSet{} +} + +func (def *AstEnumDefinition) GetOperation() string { + return "" +} + +// EnumValueDefinition implements Node, Definition +type AstEnumValueDefinition struct { + Kind string + Loc *AstLocation + Name *AstName +} + +func NewAstEnumValueDefinition(def *AstEnumValueDefinition) *AstEnumValueDefinition { + if def == nil { + def = &AstEnumValueDefinition{} + } + return &AstEnumValueDefinition{ + Kind: kinds.EnumValueDefinition, + Loc: def.Loc, + Name: def.Name, + } +} + +func (def *AstEnumValueDefinition) GetKind() string { + return def.Kind +} + +func (def *AstEnumValueDefinition) GetLoc() *AstLocation { + return def.Loc +} + +// AstInputObjectDefinition implements Node, Definition +type AstInputObjectDefinition struct { + Kind string + Loc *AstLocation + Name *AstName + Fields []*AstInputValueDefinition +} + +func NewAstInputObjectDefinition(def *AstInputObjectDefinition) *AstInputObjectDefinition { + if def == nil { + def = &AstInputObjectDefinition{} + } + return &AstInputObjectDefinition{ + Kind: kinds.InputObjectDefinition, + Loc: def.Loc, + Name: def.Name, + Fields: def.Fields, + } +} + +func (def *AstInputObjectDefinition) GetKind() string { + return def.Kind +} + +func (def *AstInputObjectDefinition) GetLoc() *AstLocation { + return def.Loc +} + +func (def *AstInputObjectDefinition) GetName() *AstName { + return def.Name +} + +func (def *AstInputObjectDefinition) GetVariableDefinitions() []*AstVariableDefinition { + return []*AstVariableDefinition{} +} + +func (def *AstInputObjectDefinition) GetSelectionSet() *AstSelectionSet { + return &AstSelectionSet{} +} + +func (def *AstInputObjectDefinition) GetOperation() string { + return "" +} + +// TypeExtensionDefinition implements Node, Definition +type AstTypeExtensionDefinition struct { + Kind string + Loc *AstLocation + Definition *AstObjectDefinition +} + +func NewAstTypeExtensionDefinition(def *AstTypeExtensionDefinition) *AstTypeExtensionDefinition { + if def == nil { + def = &AstTypeExtensionDefinition{} + } + return &AstTypeExtensionDefinition{ + Kind: kinds.TypeExtensionDefinition, + Loc: def.Loc, + Definition: def.Definition, + } +} + +func (def *AstTypeExtensionDefinition) GetKind() string { + return def.Kind +} + +func (def *AstTypeExtensionDefinition) GetLoc() *AstLocation { + return def.Loc +} + +func (def *AstTypeExtensionDefinition) GetVariableDefinitions() []*AstVariableDefinition { + return []*AstVariableDefinition{} +} + +func (def *AstTypeExtensionDefinition) GetSelectionSet() *AstSelectionSet { + return &AstSelectionSet{} +} + +func (def *AstTypeExtensionDefinition) GetOperation() string { + return "" +} diff --git a/ast_types.go b/ast_types.go new file mode 100644 index 00000000..37537a90 --- /dev/null +++ b/ast_types.go @@ -0,0 +1,106 @@ +package graphql + +import ( + "github.com/chris-ramon/graphql/kinds" +) + +type AstType interface { + GetKind() string + GetLoc() *AstLocation + String() string +} + +// Ensure that all value types implements Value interface +var _ AstType = (*AstNamed)(nil) +var _ AstType = (*AstList)(nil) +var _ AstType = (*AstNonNull)(nil) + +// AstNamed implements Node, Type +type AstNamed struct { + Kind string + Loc *AstLocation + Name *AstName +} + +func NewAstNamed(t *AstNamed) *AstNamed { + if t == nil { + t = &AstNamed{} + } + return &AstNamed{ + Kind: kinds.Named, + Loc: t.Loc, + Name: t.Name, + } +} + +func (t *AstNamed) GetKind() string { + return t.Kind +} + +func (t *AstNamed) GetLoc() *AstLocation { + return t.Loc +} + +func (t *AstNamed) String() string { + return t.GetKind() +} + +// List implements Node, Type +type AstList struct { + Kind string + Loc *AstLocation + Type AstType +} + +func NewAstList(t *AstList) *AstList { + if t == nil { + t = &AstList{} + } + return &AstList{ + Kind: kinds.List, + Loc: t.Loc, + Type: t.Type, + } +} + +func (t *AstList) GetKind() string { + return t.Kind +} + +func (t *AstList) GetLoc() *AstLocation { + return t.Loc +} + +func (t *AstList) String() string { + return t.GetKind() +} + +// AstNonNull implements Node, Type +type AstNonNull struct { + Kind string + Loc *AstLocation + Type AstType +} + +func NewAstNonNull(t *AstNonNull) *AstNonNull { + if t == nil { + t = &AstNonNull{} + } + return &AstNonNull{ + Kind: kinds.NonNull, + Loc: t.Loc, + Type: t.Type, + } +} + +func (t *AstNonNull) GetKind() string { + return t.Kind +} + +func (t *AstNonNull) GetLoc() *AstLocation { + return t.Loc +} + +func (t *AstNonNull) String() string { + return t.GetKind() +} diff --git a/ast_values.go b/ast_values.go new file mode 100644 index 00000000..7c8d84b4 --- /dev/null +++ b/ast_values.go @@ -0,0 +1,305 @@ +package graphql + +import ( + "github.com/chris-ramon/graphql/kinds" +) + +type Value interface { + GetValue() interface{} + GetKind() string + GetLoc() *AstLocation +} + +// Ensure that all value types implements Value interface +var _ Value = (*AstVariable)(nil) +var _ Value = (*AstIntValue)(nil) +var _ Value = (*AstFloatValue)(nil) +var _ Value = (*AstStringValue)(nil) +var _ Value = (*AstBooleanValue)(nil) +var _ Value = (*AstEnumValue)(nil) +var _ Value = (*AstListValue)(nil) +var _ Value = (*AstObjectValue)(nil) + +// AstVariable implements Node, Value +type AstVariable struct { + Kind string + Loc *AstLocation + Name *AstName +} + +func NewAstVariable(v *AstVariable) *AstVariable { + if v == nil { + v = &AstVariable{} + } + return &AstVariable{ + Kind: kinds.Variable, + Loc: v.Loc, + Name: v.Name, + } +} + +func (v *AstVariable) GetKind() string { + return v.Kind +} + +func (v *AstVariable) GetLoc() *AstLocation { + return v.Loc +} + +// GetValue alias to AstVariable.GetName() +func (v *AstVariable) GetValue() interface{} { + return v.GetName() +} + +func (v *AstVariable) GetName() interface{} { + return v.Name +} + +// AstIntValue implements Node, Value +type AstIntValue struct { + Kind string + Loc *AstLocation + Value string +} + +func NewAstIntValue(v *AstIntValue) *AstIntValue { + if v == nil { + v = &AstIntValue{} + } + return &AstIntValue{ + Kind: kinds.IntValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *AstIntValue) GetKind() string { + return v.Kind +} + +func (v *AstIntValue) GetLoc() *AstLocation { + return v.Loc +} + +func (v *AstIntValue) GetValue() interface{} { + return v.Value +} + +// AstFloatValue implements Node, Value +type AstFloatValue struct { + Kind string + Loc *AstLocation + Value string +} + +func NewAstFloatValue(v *AstFloatValue) *AstFloatValue { + if v == nil { + v = &AstFloatValue{} + } + return &AstFloatValue{ + Kind: kinds.FloatValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *AstFloatValue) GetKind() string { + return v.Kind +} + +func (v *AstFloatValue) GetLoc() *AstLocation { + return v.Loc +} + +func (v *AstFloatValue) GetValue() interface{} { + return v.Value +} + +// AstStringValue implements Node, Value +type AstStringValue struct { + Kind string + Loc *AstLocation + Value string +} + +func NewAstStringValue(v *AstStringValue) *AstStringValue { + if v == nil { + v = &AstStringValue{} + } + return &AstStringValue{ + Kind: kinds.StringValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *AstStringValue) GetKind() string { + return v.Kind +} + +func (v *AstStringValue) GetLoc() *AstLocation { + return v.Loc +} + +func (v *AstStringValue) GetValue() interface{} { + return v.Value +} + +// AstBooleanValue implements Node, Value +type AstBooleanValue struct { + Kind string + Loc *AstLocation + Value bool +} + +func NewAstBooleanValue(v *AstBooleanValue) *AstBooleanValue { + if v == nil { + v = &AstBooleanValue{} + } + return &AstBooleanValue{ + Kind: kinds.BooleanValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *AstBooleanValue) GetKind() string { + return v.Kind +} + +func (v *AstBooleanValue) GetLoc() *AstLocation { + return v.Loc +} + +func (v *AstBooleanValue) GetValue() interface{} { + return v.Value +} + +// AstEnumValue implements Node, Value +type AstEnumValue struct { + Kind string + Loc *AstLocation + Value string +} + +func NewAstEnumValue(v *AstEnumValue) *AstEnumValue { + if v == nil { + v = &AstEnumValue{} + } + return &AstEnumValue{ + Kind: kinds.EnumValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *AstEnumValue) GetKind() string { + return v.Kind +} + +func (v *AstEnumValue) GetLoc() *AstLocation { + return v.Loc +} + +func (v *AstEnumValue) GetValue() interface{} { + return v.Value +} + +// AstListValue implements Node, Value +type AstListValue struct { + Kind string + Loc *AstLocation + Values []Value +} + +func NewAstListValue(v *AstListValue) *AstListValue { + if v == nil { + v = &AstListValue{} + } + return &AstListValue{ + Kind: kinds.ListValue, + Loc: v.Loc, + Values: v.Values, + } +} + +func (v *AstListValue) GetKind() string { + return v.Kind +} + +func (v *AstListValue) GetLoc() *AstLocation { + return v.Loc +} + +// GetValue alias to AstListValue.GetValues() +func (v *AstListValue) GetValue() interface{} { + return v.GetValues() +} + +func (v *AstListValue) GetValues() interface{} { + // TODO: verify AstObjectValue.GetValue() + return v.Values +} + +// AstObjectValue implements Node, Value +type AstObjectValue struct { + Kind string + Loc *AstLocation + Fields []*AstObjectField +} + +func NewAstObjectValue(v *AstObjectValue) *AstObjectValue { + if v == nil { + v = &AstObjectValue{} + } + return &AstObjectValue{ + Kind: kinds.ObjectValue, + Loc: v.Loc, + Fields: v.Fields, + } +} + +func (v *AstObjectValue) GetKind() string { + return v.Kind +} + +func (v *AstObjectValue) GetLoc() *AstLocation { + return v.Loc +} + +func (v *AstObjectValue) GetValue() interface{} { + // TODO: verify AstObjectValue.GetValue() + return v.Fields +} + +// AstObjectField implements Node, Value +type AstObjectField struct { + Kind string + Name *AstName + Loc *AstLocation + Value Value +} + +func NewAstObjectField(f *AstObjectField) *AstObjectField { + if f == nil { + f = &AstObjectField{} + } + return &AstObjectField{ + Kind: kinds.ObjectField, + Loc: f.Loc, + Name: f.Name, + Value: f.Value, + } +} + +func (f *AstObjectField) GetKind() string { + return f.Kind +} + +func (f *AstObjectField) GetLoc() *AstLocation { + return f.Loc +} + +func (f *AstObjectField) GetValue() interface{} { + return f.Value +} diff --git a/types/definition.go b/definition.go similarity index 90% rename from types/definition.go rename to definition.go index f5ee884c..77f9aa13 100644 --- a/types/definition.go +++ b/definition.go @@ -1,16 +1,13 @@ -package types +package graphql import ( "errors" "fmt" "reflect" "regexp" - - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/ast" ) -// These are all of the possible kinds of types. +// These are all of the possible kinds of type Type interface { GetName() string GetDescription() string @@ -43,34 +40,34 @@ var _ Input = (*List)(nil) var _ Input = (*NonNull)(nil) func IsInputType(ttype Type) bool { - namedType := GetNamedType(ttype) - if _, ok := namedType.(*Scalar); ok { + Named := GetNamed(ttype) + if _, ok := Named.(*Scalar); ok { return true } - if _, ok := namedType.(*Enum); ok { + if _, ok := Named.(*Enum); ok { return true } - if _, ok := namedType.(*InputObject); ok { + if _, ok := Named.(*InputObject); ok { return true } return false } func IsOutputType(ttype Type) bool { - namedType := GetNamedType(ttype) - if _, ok := namedType.(*Scalar); ok { + Named := GetNamed(ttype) + if _, ok := Named.(*Scalar); ok { return true } - if _, ok := namedType.(*Object); ok { + if _, ok := Named.(*Object); ok { return true } - if _, ok := namedType.(*Interface); ok { + if _, ok := Named.(*Interface); ok { return true } - if _, ok := namedType.(*Union); ok { + if _, ok := Named.(*Union); ok { return true } - if _, ok := namedType.(*Enum); ok { + if _, ok := Named.(*Enum); ok { return true } return false @@ -123,7 +120,7 @@ var _ Named = (*Union)(nil) var _ Named = (*Enum)(nil) var _ Named = (*InputObject)(nil) -func GetNamedType(ttype Type) Named { +func GetNamed(ttype Type) Named { unmodifiedType := ttype for { if ttype, ok := unmodifiedType.(*List); ok { @@ -165,7 +162,7 @@ type Scalar struct { } type SerializeFn func(value interface{}) interface{} type ParseValueFn func(value interface{}) interface{} -type ParseLiteralFn func(valueAST ast.Value) interface{} +type ParseLiteralFn func(valueAST Value) interface{} type ScalarConfig struct { Name string `json:"name"` Description string `json:"description"` @@ -227,7 +224,7 @@ func (st *Scalar) ParseValue(value interface{}) interface{} { } return st.scalarConfig.ParseValue(value) } -func (st *Scalar) ParseLiteral(valueAST ast.Value) interface{} { +func (st *Scalar) ParseLiteral(valueAST Value) interface{} { if st.scalarConfig.ParseLiteral == nil { return nil } @@ -250,7 +247,7 @@ func (st *Scalar) GetError() error { /** * Object Type Definition * - * Almost all of the GraphQL types you define will be object types. Object types + * Almost all of the GraphQL types you define will be object Object types * have a name, but most importantly describe their fields. * * Example: @@ -301,11 +298,11 @@ type IsTypeOfFn func(value interface{}, info ResolveInfo) bool type InterfacesThunk func() []*Interface type ObjectConfig struct { - Name string `json:"description"` - Interfaces interface{} `json:"interfaces"` + Name string `json:"description"` + Interfaces interface{} `json:"interfaces"` Fields FieldConfigMap `json:"fields"` - IsTypeOf IsTypeOfFn `json:"isTypeOf"` - Description string `json:"description"` + IsTypeOf IsTypeOfFn `json:"isTypeOf"` + Description string `json:"description"` } func NewObject(config ObjectConfig) *Object { @@ -332,7 +329,7 @@ func NewObject(config ObjectConfig) *Object { Update the interfaces to know about this implementation. This is an rare and unfortunate use of mutation in the type definition implementations, but avoids an expensive "getPossibleTypes" - implementation for Interface types. + implementation for Interface */ interfaces := objectType.GetInterfaces() if interfaces == nil { @@ -503,21 +500,21 @@ type FieldResolveFn func(p GQLFRParams) interface{} type ResolveInfo struct { FieldName string - FieldASTs []*ast.Field + FieldASTs []*AstField ReturnType Output ParentType Composite Schema Schema - Fragments map[string]ast.Definition + Fragments map[string]Definition RootValue interface{} - Operation ast.Definition + Operation Definition VariableValues map[string]interface{} } type FieldConfigMap map[string]*FieldConfig type FieldConfig struct { - Name string `json:"name"` // used by graphlql-relay - Type Output `json:"type"` + Name string `json:"name"` // used by graphlql-relay + Type Output `json:"type"` Args FieldConfigArgument `json:"args"` Resolve FieldResolveFn DeprecationReason string `json:"deprecationReason"` @@ -527,33 +524,33 @@ type FieldConfig struct { type FieldConfigArgument map[string]*ArgumentConfig type ArgumentConfig struct { - Type Input `json:"type"` - DefaultValue interface{} `json:"defaultValue"` - Description string `json:"description"` + Type Input `json:"type"` + DefaultValue interface{} `json:"defaultValue"` + Description string `json:"description"` } type FieldDefinitionMap map[string]*FieldDefinition type FieldDefinition struct { - Name string `json:"name"` - Description string `json:"description"` - Type Output `json:"type"` + Name string `json:"name"` + Description string `json:"description"` + Type Output `json:"type"` Args []*Argument `json:"args"` Resolve FieldResolveFn `json:"-"` - DeprecationReason string `json:"deprecationReason"` + DeprecationReason string `json:"deprecationReason"` } type FieldArgument struct { Name string `json:"name"` - Type Type `json:"type"` + Type Type `json:"type"` DefaultValue interface{} `json:"defaultValue"` Description string `json:"description"` } type Argument struct { - Name string `json:"name"` - Type Input `json:"type"` - DefaultValue interface{} `json:"defaultValue"` - Description string `json:"description"` + Name string `json:"name"` + Type Input `json:"type"` + DefaultValue interface{} `json:"defaultValue"` + Description string `json:"description"` } func (st *Argument) GetName() string { @@ -601,7 +598,7 @@ type Interface struct { err error } type InterfaceConfig struct { - Name string `json:"name"` + Name string `json:"name"` Fields FieldConfigMap `json:"fields"` ResolveType ResolveTypeFn Description string `json:"description"` @@ -729,7 +726,7 @@ type Union struct { err error } type UnionConfig struct { - Name string `json:"name"` + Name string `json:"name"` Types []*Object `json:"types"` ResolveType ResolveTypeFn Description string `json:"description"` @@ -870,9 +867,9 @@ type EnumValueConfig struct { Description string `json:"description"` } type EnumConfig struct { - Name string `json:"name"` + Name string `json:"name"` Values EnumValueConfigMap `json:"values"` - Description string `json:"description"` + Description string `json:"description"` } type EnumValueDefinition struct { Name string `json:"name"` @@ -957,8 +954,8 @@ func (gt *Enum) ParseValue(value interface{}) interface{} { } return nil } -func (gt *Enum) ParseLiteral(valueAST ast.Value) interface{} { - if valueAST, ok := valueAST.(*ast.EnumValue); ok { +func (gt *Enum) ParseLiteral(valueAST Value) interface{} { + if valueAST, ok := valueAST.(*AstEnumValue); ok { if enumValue, ok := gt.getNameLookup()[valueAST.Value]; ok { return enumValue.Value } @@ -1031,15 +1028,15 @@ type InputObject struct { err error } type InputObjectFieldConfig struct { - Type Input `json:"type"` - DefaultValue interface{} `json:"defaultValue"` - Description string `json:"description"` + Type Input `json:"type"` + DefaultValue interface{} `json:"defaultValue"` + Description string `json:"description"` } type InputObjectField struct { - Name string `json:"name"` - Type Input `json:"type"` - DefaultValue interface{} `json:"defaultValue"` - Description string `json:"description"` + Name string `json:"name"` + Type Input `json:"type"` + DefaultValue interface{} `json:"defaultValue"` + Description string `json:"description"` } func (st *InputObjectField) GetName() string { @@ -1214,8 +1211,8 @@ func (gl *List) GetError() error { * Note: the enforcement of non-nullability occurs within the executor. */ type NonNull struct { - Name string `json:"name"` // added to conform with introspection for NonNull.Name = nil - OfType Type `json:"ofType"` + Name string `json:"name"` // added to conform with introspection for NonNull.Name = nil + OfType Type `json:"ofType"` err error } @@ -1256,11 +1253,3 @@ func assertValidName(name string) error { fmt.Sprintf(`Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "%v" does not.`, name), ) } - -// TODO: there is another invariant() func in `executor` -func invariant(condition bool, message string) error { - if !condition { - return graphqlerrors.NewFormattedError(message) - } - return nil -} diff --git a/types/definition_test.go b/definition_test.go similarity index 54% rename from types/definition_test.go rename to definition_test.go index 32e1cfc4..bd44eb4a 100644 --- a/types/definition_test.go +++ b/definition_test.go @@ -1,130 +1,127 @@ -package types_test +package graphql import ( "fmt" "reflect" "testing" - - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" ) -var blogImage = types.NewObject(types.ObjectConfig{ +var blogImage = NewObject(ObjectConfig{ Name: "Image", - Fields: types.FieldConfigMap{ - "url": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "url": &FieldConfig{ + Type: String, }, - "width": &types.FieldConfig{ - Type: types.Int, + "width": &FieldConfig{ + Type: Int, }, - "height": &types.FieldConfig{ - Type: types.Int, + "height": &FieldConfig{ + Type: Int, }, }, }) -var blogAuthor = types.NewObject(types.ObjectConfig{ +var blogAuthor = NewObject(ObjectConfig{ Name: "Author", - Fields: types.FieldConfigMap{ - "id": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "id": &FieldConfig{ + Type: String, }, - "name": &types.FieldConfig{ - Type: types.String, + "name": &FieldConfig{ + Type: String, }, - "pic": &types.FieldConfig{ + "pic": &FieldConfig{ Type: blogImage, - Args: types.FieldConfigArgument{ - "width": &types.ArgumentConfig{ - Type: types.Int, + Args: FieldConfigArgument{ + "width": &ArgumentConfig{ + Type: Int, }, - "height": &types.ArgumentConfig{ - Type: types.Int, + "height": &ArgumentConfig{ + Type: Int, }, }, }, - "recentArticle": &types.FieldConfig{}, + "recentArticle": &FieldConfig{}, }, }) -var blogArticle = types.NewObject(types.ObjectConfig{ +var blogArticle = NewObject(ObjectConfig{ Name: "Article", - Fields: types.FieldConfigMap{ - "id": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "id": &FieldConfig{ + Type: String, }, - "isPublished": &types.FieldConfig{ - Type: types.Boolean, + "isPublished": &FieldConfig{ + Type: Boolean, }, - "author": &types.FieldConfig{ + "author": &FieldConfig{ Type: blogAuthor, }, - "title": &types.FieldConfig{ - Type: types.String, + "title": &FieldConfig{ + Type: String, }, - "body": &types.FieldConfig{ - Type: types.String, + "body": &FieldConfig{ + Type: String, }, }, }) -var blogQuery = types.NewObject(types.ObjectConfig{ +var blogQuery = NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "article": &types.FieldConfig{ + Fields: FieldConfigMap{ + "article": &FieldConfig{ Type: blogArticle, - Args: types.FieldConfigArgument{ - "id": &types.ArgumentConfig{ - Type: types.String, + Args: FieldConfigArgument{ + "id": &ArgumentConfig{ + Type: String, }, }, }, - "feed": &types.FieldConfig{ - Type: types.NewList(blogArticle), + "feed": &FieldConfig{ + Type: NewList(blogArticle), }, }, }) -var blogMutation = types.NewObject(types.ObjectConfig{ +var blogMutation = NewObject(ObjectConfig{ Name: "Mutation", - Fields: types.FieldConfigMap{ - "writeArticle": &types.FieldConfig{ + Fields: FieldConfigMap{ + "writeArticle": &FieldConfig{ Type: blogArticle, }, }, }) -var objectType = types.NewObject(types.ObjectConfig{ +var objectType = NewObject(ObjectConfig{ Name: "Object", - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { return true }, }) -var interfaceType = types.NewInterface(types.InterfaceConfig{ +var interfaceType = NewInterface(InterfaceConfig{ Name: "Interface", }) -var unionType = types.NewUnion(types.UnionConfig{ +var unionType = NewUnion(UnionConfig{ Name: "Union", - Types: []*types.Object{ + Types: []*Object{ objectType, }, }) -var enumType = types.NewEnum(types.EnumConfig{ +var enumType = NewEnum(EnumConfig{ Name: "Enum", - Values: types.EnumValueConfigMap{ - "foo": &types.EnumValueConfig{}, + Values: EnumValueConfigMap{ + "foo": &EnumValueConfig{}, }, }) -var inputObjectType = types.NewInputObject(types.InputObjectConfig{ +var inputObjectType = NewInputObject(InputObjectConfig{ Name: "InputObject", }) func init() { - blogAuthor.AddFieldConfig("recentArticle", &types.FieldConfig{ + blogAuthor.AddFieldConfig("recentArticle", &FieldConfig{ Type: blogArticle, }) } func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { - blogSchema, err := types.NewSchema(types.SchemaConfig{ + blogSchema, err := NewSchema(SchemaConfig{ Query: blogQuery, }) if err != nil { @@ -149,9 +146,9 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { if articleField.Name != "article" { t.Fatalf("articleField.Name expected to equal `article`, got: %v", articleField.Name) } - articleFieldTypeObject, ok := articleFieldType.(*types.Object) + articleFieldTypeObject, ok := articleFieldType.(*Object) if !ok { - t.Fatalf("expected articleFieldType to be *types.Object`, got: %v", articleField) + t.Fatalf("expected articleFieldType to be *Object`, got: %v", articleField) } // TODO: expose a Object.GetField(key string), instead of this ghetto way of accessing a field map? @@ -162,8 +159,8 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { if titleField.Name != "title" { t.Fatalf("titleField.Name expected to equal title, got: %v", titleField.Name) } - if titleField.Type != types.String { - t.Fatalf("titleField.Type expected to equal types.String, got: %v", titleField.Type) + if titleField.Type != String { + t.Fatalf("titleField.Type expected to equal String, got: %v", titleField.Type) } if titleField.Type.GetName() != "String" { t.Fatalf("titleField.Type.GetName() expected to equal `String`, got: %v", titleField.Type.GetName()) @@ -173,9 +170,9 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { if authorField == nil { t.Fatalf("authorField is nil") } - authorFieldObject, ok := authorField.Type.(*types.Object) + authorFieldObject, ok := authorField.Type.(*Object) if !ok { - t.Fatalf("expected authorField.Type to be *types.Object`, got: %v", authorField) + t.Fatalf("expected authorField.Type to be Object`, got: %v", authorField) } recentArticleField := authorFieldObject.GetFields()["recentArticle"] @@ -187,9 +184,9 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { } feedField := blogQuery.GetFields()["feed"] - feedFieldList, ok := feedField.Type.(*types.List) + feedFieldList, ok := feedField.Type.(*List) if !ok { - t.Fatalf("expected feedFieldList to be *types.List`, got: %v", authorField) + t.Fatalf("expected feedFieldList to be List`, got: %v", authorField) } if feedFieldList.OfType != blogArticle { t.Fatalf("feedFieldList.OfType expected to equal blogArticle, got: %v", feedFieldList.OfType) @@ -199,7 +196,7 @@ func TestTypeSystem_DefinitionExample_DefinesAQueryOnlySchema(t *testing.T) { } } func TestTypeSystem_DefinitionExample_DefinesAMutationScheme(t *testing.T) { - blogSchema, err := types.NewSchema(types.SchemaConfig{ + blogSchema, err := NewSchema(SchemaConfig{ Query: blogQuery, Mutation: blogMutation, }) @@ -228,36 +225,36 @@ func TestTypeSystem_DefinitionExample_DefinesAMutationScheme(t *testing.T) { } func TestTypeSystem_DefinitionExample_IncludesNestedInputObjectsInTheMap(t *testing.T) { - nestedInputObject := types.NewInputObject(types.InputObjectConfig{ + nestedInputObject := NewInputObject(InputObjectConfig{ Name: "NestedInputObject", - Fields: types.InputObjectConfigFieldMap{ - "value": &types.InputObjectFieldConfig{ - Type: types.String, + Fields: InputObjectConfigFieldMap{ + "value": &InputObjectFieldConfig{ + Type: String, }, }, }) - someInputObject := types.NewInputObject(types.InputObjectConfig{ + someInputObject := NewInputObject(InputObjectConfig{ Name: "SomeInputObject", - Fields: types.InputObjectConfigFieldMap{ - "nested": &types.InputObjectFieldConfig{ + Fields: InputObjectConfigFieldMap{ + "nested": &InputObjectFieldConfig{ Type: nestedInputObject, }, }, }) - someMutation := types.NewObject(types.ObjectConfig{ + someMutation := NewObject(ObjectConfig{ Name: "SomeMutation", - Fields: types.FieldConfigMap{ - "mutateSomething": &types.FieldConfig{ + Fields: FieldConfigMap{ + "mutateSomething": &FieldConfig{ Type: blogArticle, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ Type: someInputObject, }, }, }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: blogQuery, Mutation: someMutation, }) @@ -271,32 +268,32 @@ func TestTypeSystem_DefinitionExample_IncludesNestedInputObjectsInTheMap(t *test func TestTypeSystem_DefinitionExample_IncludesInterfacesSubTypesInTheTypeMap(t *testing.T) { - someInterface := types.NewInterface(types.InterfaceConfig{ + someInterface := NewInterface(InterfaceConfig{ Name: "SomeInterface", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.Int, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: Int, }, }, }) - someSubType := types.NewObject(types.ObjectConfig{ + someSubType := NewObject(ObjectConfig{ Name: "SomeSubtype", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.Int, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: Int, }, }, - Interfaces: []*types.Interface{someInterface}, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + Interfaces: []*Interface{someInterface}, + IsTypeOf: func(value interface{}, info ResolveInfo) bool { return true }, }) - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "iface": &types.FieldConfig{ + Fields: FieldConfigMap{ + "iface": &FieldConfig{ Type: someInterface, }, }, @@ -312,34 +309,34 @@ func TestTypeSystem_DefinitionExample_IncludesInterfacesSubTypesInTheTypeMap(t * func TestTypeSystem_DefinitionExample_IncludesInterfacesThunkSubtypesInTheTypeMap(t *testing.T) { - someInterface := types.NewInterface(types.InterfaceConfig{ + someInterface := NewInterface(InterfaceConfig{ Name: "SomeInterface", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.Int, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: Int, }, }, }) - someSubType := types.NewObject(types.ObjectConfig{ + someSubType := NewObject(ObjectConfig{ Name: "SomeSubtype", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.Int, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: Int, }, }, - Interfaces: (types.InterfacesThunk)(func() []*types.Interface { - return []*types.Interface{someInterface} + Interfaces: (InterfacesThunk)(func() []*Interface { + return []*Interface{someInterface} }), - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { return true }, }) - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "iface": &types.FieldConfig{ + Fields: FieldConfigMap{ + "iface": &FieldConfig{ Type: someInterface, }, }, @@ -356,21 +353,21 @@ func TestTypeSystem_DefinitionExample_IncludesInterfacesThunkSubtypesInTheTypeMa func TestTypeSystem_DefinitionExample_StringifiesSimpleTypes(t *testing.T) { type Test struct { - ttype types.Type + ttype Type expected string } tests := []Test{ - Test{types.Int, "Int"}, + Test{Int, "Int"}, Test{blogArticle, "Article"}, Test{interfaceType, "Interface"}, Test{unionType, "Union"}, Test{enumType, "Enum"}, Test{inputObjectType, "InputObject"}, - Test{types.NewNonNull(types.Int), "Int!"}, - Test{types.NewList(types.Int), "[Int]"}, - Test{types.NewNonNull(types.NewList(types.Int)), "[Int]!"}, - Test{types.NewList(types.NewNonNull(types.Int)), "[Int!]"}, - Test{types.NewList(types.NewList(types.Int)), "[[Int]]"}, + Test{NewNonNull(Int), "Int!"}, + Test{NewList(Int), "[Int]"}, + Test{NewNonNull(NewList(Int)), "[Int]!"}, + Test{NewList(NewNonNull(Int)), "[Int!]"}, + Test{NewList(NewList(Int)), "[[Int]]"}, } for _, test := range tests { ttypeStr := fmt.Sprintf("%v", test.ttype) @@ -382,11 +379,11 @@ func TestTypeSystem_DefinitionExample_StringifiesSimpleTypes(t *testing.T) { func TestTypeSystem_DefinitionExample_IdentifiesInputTypes(t *testing.T) { type Test struct { - ttype types.Type + ttype Type expected bool } tests := []Test{ - Test{types.Int, true}, + Test{Int, true}, Test{objectType, false}, Test{interfaceType, false}, Test{unionType, false}, @@ -395,13 +392,13 @@ func TestTypeSystem_DefinitionExample_IdentifiesInputTypes(t *testing.T) { } for _, test := range tests { ttypeStr := fmt.Sprintf("%v", test.ttype) - if types.IsInputType(test.ttype) != test.expected { + if IsInputType(test.ttype) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } - if types.IsInputType(types.NewList(test.ttype)) != test.expected { + if IsInputType(NewList(test.ttype)) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } - if types.IsInputType(types.NewNonNull(test.ttype)) != test.expected { + if IsInputType(NewNonNull(test.ttype)) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } } @@ -409,11 +406,11 @@ func TestTypeSystem_DefinitionExample_IdentifiesInputTypes(t *testing.T) { func TestTypeSystem_DefinitionExample_IdentifiesOutputTypes(t *testing.T) { type Test struct { - ttype types.Type + ttype Type expected bool } tests := []Test{ - Test{types.Int, true}, + Test{Int, true}, Test{objectType, true}, Test{interfaceType, true}, Test{unionType, true}, @@ -422,36 +419,36 @@ func TestTypeSystem_DefinitionExample_IdentifiesOutputTypes(t *testing.T) { } for _, test := range tests { ttypeStr := fmt.Sprintf("%v", test.ttype) - if types.IsOutputType(test.ttype) != test.expected { + if IsOutputType(test.ttype) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } - if types.IsOutputType(types.NewList(test.ttype)) != test.expected { + if IsOutputType(NewList(test.ttype)) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } - if types.IsOutputType(types.NewNonNull(test.ttype)) != test.expected { + if IsOutputType(NewNonNull(test.ttype)) != test.expected { t.Fatalf(`expected %v , got: %v`, test.expected, ttypeStr) } } } func TestTypeSystem_DefinitionExample_ProhibitsNestingNonNullInsideNonNull(t *testing.T) { - ttype := types.NewNonNull(types.NewNonNull(types.Int)) + ttype := NewNonNull(NewNonNull(Int)) expected := `Can only create NonNull of a Nullable Type but got: Int!.` if ttype.GetError().Error() != expected { t.Fatalf(`expected %v , got: %v`, expected, ttype.GetError()) } } func TestTypeSystem_DefinitionExample_ProhibitsNilInNonNull(t *testing.T) { - ttype := types.NewNonNull(nil) + ttype := NewNonNull(nil) expected := `Can only create NonNull of a Nullable Type but got: .` if ttype.GetError().Error() != expected { t.Fatalf(`expected %v , got: %v`, expected, ttype.GetError()) } } func TestTypeSystem_DefinitionExample_ProhibitsNilTypeInUnions(t *testing.T) { - ttype := types.NewUnion(types.UnionConfig{ + ttype := NewUnion(UnionConfig{ Name: "BadUnion", - Types: []*types.Object{nil}, + Types: []*Object{nil}, }) expected := `BadUnion may only contain Object types, it cannot contain: .` if ttype.GetError().Error() != expected { @@ -459,77 +456,77 @@ func TestTypeSystem_DefinitionExample_ProhibitsNilTypeInUnions(t *testing.T) { } } func TestTypeSystem_DefinitionExample_DoesNotMutatePassedFieldDefinitions(t *testing.T) { - fields := types.FieldConfigMap{ - "field1": &types.FieldConfig{ - Type: types.String, + fields := FieldConfigMap{ + "field1": &FieldConfig{ + Type: String, }, - "field2": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "id": &types.ArgumentConfig{ - Type: types.String, + "field2": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "id": &ArgumentConfig{ + Type: String, }, }, }, } - testObject1 := types.NewObject(types.ObjectConfig{ + testObject1 := NewObject(ObjectConfig{ Name: "Test1", Fields: fields, }) - testObject2 := types.NewObject(types.ObjectConfig{ + testObject2 := NewObject(ObjectConfig{ Name: "Test2", Fields: fields, }) if !reflect.DeepEqual(testObject1.GetFields(), testObject2.GetFields()) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(testObject1.GetFields(), testObject2.GetFields())) + t.Fatalf("Unexpected result, Diff: %v", Diff(testObject1.GetFields(), testObject2.GetFields())) } - expectedFields := types.FieldConfigMap{ - "field1": &types.FieldConfig{ - Type: types.String, + expectedFields := FieldConfigMap{ + "field1": &FieldConfig{ + Type: String, }, - "field2": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "id": &types.ArgumentConfig{ - Type: types.String, + "field2": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "id": &ArgumentConfig{ + Type: String, }, }, }, } if !reflect.DeepEqual(fields, expectedFields) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedFields, fields)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expectedFields, fields)) } - inputFields := types.InputObjectConfigFieldMap{ - "field1": &types.InputObjectFieldConfig{ - Type: types.String, + inputFields := InputObjectConfigFieldMap{ + "field1": &InputObjectFieldConfig{ + Type: String, }, - "field2": &types.InputObjectFieldConfig{ - Type: types.String, + "field2": &InputObjectFieldConfig{ + Type: String, }, } - expectedInputFields := types.InputObjectConfigFieldMap{ - "field1": &types.InputObjectFieldConfig{ - Type: types.String, + expectedInputFields := InputObjectConfigFieldMap{ + "field1": &InputObjectFieldConfig{ + Type: String, }, - "field2": &types.InputObjectFieldConfig{ - Type: types.String, + "field2": &InputObjectFieldConfig{ + Type: String, }, } - testInputObject1 := types.NewInputObject(types.InputObjectConfig{ + testInputObject1 := NewInputObject(InputObjectConfig{ Name: "Test1", Fields: inputFields, }) - testInputObject2 := types.NewInputObject(types.InputObjectConfig{ + testInputObject2 := NewInputObject(InputObjectConfig{ Name: "Test2", Fields: inputFields, }) if !reflect.DeepEqual(testInputObject1.GetFields(), testInputObject2.GetFields()) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(testInputObject1.GetFields(), testInputObject2.GetFields())) + t.Fatalf("Unexpected result, Diff: %v", Diff(testInputObject1.GetFields(), testInputObject2.GetFields())) } if !reflect.DeepEqual(inputFields, expectedInputFields) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedInputFields, fields)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expectedInputFields, fields)) } } diff --git a/types/directives.go b/directives.go similarity index 84% rename from types/directives.go rename to directives.go index 93cdb820..fbbcc18e 100644 --- a/types/directives.go +++ b/directives.go @@ -1,12 +1,12 @@ -package types +package graphql type Directive struct { - Name string `json:"name"` - Description string `json:"description"` + Name string `json:"name"` + Description string `json:"description"` Args []*Argument `json:"args"` - OnOperation bool `json:"onOperation"` - OnFragment bool `json:"onFragment"` - OnField bool `json:"onField"` + OnOperation bool `json:"onOperation"` + OnFragment bool `json:"onFragment"` + OnField bool `json:"onField"` } /** diff --git a/executor/directives_test.go b/directives_test.go similarity index 77% rename from executor/directives_test.go rename to directives_test.go index d416f855..21351402 100644 --- a/executor/directives_test.go +++ b/directives_test.go @@ -1,22 +1,19 @@ -package executor_test +package graphql import ( - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) -var directivesTestSchema, _ = types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ +var directivesTestSchema, _ = NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "TestType", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, - "b": &types.FieldConfig{ - Type: types.String, + "b": &FieldConfig{ + Type: String, }, }, }), @@ -27,19 +24,19 @@ var directivesTestData map[string]interface{} = map[string]interface{}{ "b": func() interface{} { return "b" }, } -func executeDirectivesTestQuery(t *testing.T, doc string) *types.Result { - ast := testutil.Parse(t, doc) - ep := executor.ExecuteParams{ +func executeDirectivesTestQuery(t *testing.T, doc string) *Result { + ast := TestParse(t, doc) + ep := ExecuteParams{ Schema: directivesTestSchema, AST: ast, Root: directivesTestData, } - return testutil.Execute(t, ep) + return TestExecute(t, ep) } func TestDirectivesWorksWithoutDirectives(t *testing.T) { query := `{ a, b }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -50,13 +47,13 @@ func TestDirectivesWorksWithoutDirectives(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestDirectivesWorksOnScalarsIfTrueIncludesScalar(t *testing.T) { query := `{ a, b @include(if: true) }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -67,13 +64,13 @@ func TestDirectivesWorksOnScalarsIfTrueIncludesScalar(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestDirectivesWorksOnScalarsIfFalseOmitsOnScalar(t *testing.T) { query := `{ a, b @include(if: false) }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", }, @@ -83,13 +80,13 @@ func TestDirectivesWorksOnScalarsIfFalseOmitsOnScalar(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestDirectivesWorksOnScalarsUnlessFalseIncludesScalar(t *testing.T) { query := `{ a, b @skip(if: false) }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -100,13 +97,13 @@ func TestDirectivesWorksOnScalarsUnlessFalseIncludesScalar(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestDirectivesWorksOnScalarsUnlessTrueOmitsScalar(t *testing.T) { query := `{ a, b @skip(if: true) }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", }, @@ -116,7 +113,7 @@ func TestDirectivesWorksOnScalarsUnlessTrueOmitsScalar(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -130,7 +127,7 @@ func TestDirectivesWorksOnFragmentSpreadsIfFalseOmitsFragmentSpread(t *testing.T b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", }, @@ -140,7 +137,7 @@ func TestDirectivesWorksOnFragmentSpreadsIfFalseOmitsFragmentSpread(t *testing.T t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -154,7 +151,7 @@ func TestDirectivesWorksOnFragmentSpreadsIfTrueIncludesFragmentSpread(t *testing b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -165,7 +162,7 @@ func TestDirectivesWorksOnFragmentSpreadsIfTrueIncludesFragmentSpread(t *testing t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -179,7 +176,7 @@ func TestDirectivesWorksOnFragmentSpreadsUnlessFalseIncludesFragmentSpread(t *te b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -190,7 +187,7 @@ func TestDirectivesWorksOnFragmentSpreadsUnlessFalseIncludesFragmentSpread(t *te t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -204,7 +201,7 @@ func TestDirectivesWorksOnFragmentSpreadsUnlessTrueOmitsFragmentSpread(t *testin b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", }, @@ -214,7 +211,7 @@ func TestDirectivesWorksOnFragmentSpreadsUnlessTrueOmitsFragmentSpread(t *testin t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -230,7 +227,7 @@ func TestDirectivesWorksOnInlineFragmentIfFalseOmitsInlineFragment(t *testing.T) b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", }, @@ -240,7 +237,7 @@ func TestDirectivesWorksOnInlineFragmentIfFalseOmitsInlineFragment(t *testing.T) t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -256,7 +253,7 @@ func TestDirectivesWorksOnInlineFragmentIfTrueIncludesInlineFragment(t *testing. b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -267,7 +264,7 @@ func TestDirectivesWorksOnInlineFragmentIfTrueIncludesInlineFragment(t *testing. t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -283,7 +280,7 @@ func TestDirectivesWorksOnInlineFragmentUnlessFalseIncludesInlineFragment(t *tes b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -294,7 +291,7 @@ func TestDirectivesWorksOnInlineFragmentUnlessFalseIncludesInlineFragment(t *tes t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -310,7 +307,7 @@ func TestDirectivesWorksOnInlineFragmentUnlessTrueIncludesInlineFragment(t *test b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", }, @@ -320,7 +317,7 @@ func TestDirectivesWorksOnInlineFragmentUnlessTrueIncludesInlineFragment(t *test t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -334,7 +331,7 @@ func TestDirectivesWorksOnFragmentIfFalseOmitsFragment(t *testing.T) { b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", }, @@ -344,7 +341,7 @@ func TestDirectivesWorksOnFragmentIfFalseOmitsFragment(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -358,7 +355,7 @@ func TestDirectivesWorksOnFragmentIfTrueIncludesFragment(t *testing.T) { b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -369,7 +366,7 @@ func TestDirectivesWorksOnFragmentIfTrueIncludesFragment(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -383,7 +380,7 @@ func TestDirectivesWorksOnFragmentUnlessFalseIncludesFragment(t *testing.T) { b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -394,7 +391,7 @@ func TestDirectivesWorksOnFragmentUnlessFalseIncludesFragment(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -408,7 +405,7 @@ func TestDirectivesWorksOnFragmentUnlessTrueOmitsFragment(t *testing.T) { b } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", }, @@ -418,6 +415,6 @@ func TestDirectivesWorksOnFragmentUnlessTrueOmitsFragment(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/types/enum_type_test.go b/enum_type_test.go similarity index 64% rename from types/enum_type_test.go rename to enum_type_test.go index 742f8056..02ad10df 100644 --- a/types/enum_type_test.go +++ b/enum_type_test.go @@ -1,45 +1,41 @@ -package types_test +package graphql import ( - "github.com/chris-ramon/graphql" - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) -var enumTypeTestColorType = types.NewEnum(types.EnumConfig{ +var enumTypeTestColorType = NewEnum(EnumConfig{ Name: "Color", - Values: types.EnumValueConfigMap{ - "RED": &types.EnumValueConfig{ + Values: EnumValueConfigMap{ + "RED": &EnumValueConfig{ Value: 0, }, - "GREEN": &types.EnumValueConfig{ + "GREEN": &EnumValueConfig{ Value: 1, }, - "BLUE": &types.EnumValueConfig{ + "BLUE": &EnumValueConfig{ Value: 2, }, }, }) -var enumTypeTestQueryType = types.NewObject(types.ObjectConfig{ +var enumTypeTestQueryType = NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "colorEnum": &types.FieldConfig{ + Fields: FieldConfigMap{ + "colorEnum": &FieldConfig{ Type: enumTypeTestColorType, - Args: types.FieldConfigArgument{ - "fromEnum": &types.ArgumentConfig{ + Args: FieldConfigArgument{ + "fromEnum": &ArgumentConfig{ Type: enumTypeTestColorType, }, - "fromInt": &types.ArgumentConfig{ - Type: types.Int, + "fromInt": &ArgumentConfig{ + Type: Int, }, - "fromString": &types.ArgumentConfig{ - Type: types.String, + "fromString": &ArgumentConfig{ + Type: String, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if fromInt, ok := p.Args["fromInt"]; ok { return fromInt } @@ -52,17 +48,17 @@ var enumTypeTestQueryType = types.NewObject(types.ObjectConfig{ return nil }, }, - "colorInt": &types.FieldConfig{ - Type: types.Int, - Args: types.FieldConfigArgument{ - "fromEnum": &types.ArgumentConfig{ + "colorInt": &FieldConfig{ + Type: Int, + Args: FieldConfigArgument{ + "fromEnum": &ArgumentConfig{ Type: enumTypeTestColorType, }, - "fromInt": &types.ArgumentConfig{ - Type: types.Int, + "fromInt": &ArgumentConfig{ + Type: Int, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if fromInt, ok := p.Args["fromInt"]; ok { return fromInt } @@ -74,17 +70,17 @@ var enumTypeTestQueryType = types.NewObject(types.ObjectConfig{ }, }, }) -var enumTypeTestMutationType = types.NewObject(types.ObjectConfig{ +var enumTypeTestMutationType = NewObject(ObjectConfig{ Name: "Mutation", - Fields: types.FieldConfigMap{ - "favoriteEnum": &types.FieldConfig{ + Fields: FieldConfigMap{ + "favoriteEnum": &FieldConfig{ Type: enumTypeTestColorType, - Args: types.FieldConfigArgument{ - "color": &types.ArgumentConfig{ + Args: FieldConfigArgument{ + "color": &ArgumentConfig{ Type: enumTypeTestColorType, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if color, ok := p.Args["color"]; ok { return color } @@ -93,20 +89,20 @@ var enumTypeTestMutationType = types.NewObject(types.ObjectConfig{ }, }, }) -var enumTypeTestSchema, _ = types.NewSchema(types.SchemaConfig{ +var enumTypeTestSchema, _ = NewSchema(SchemaConfig{ Query: enumTypeTestQueryType, Mutation: enumTypeTestMutationType, }) -func executeEnumTypeTest(t *testing.T, query string) *types.Result { - result := g(t, graphql.Params{ +func executeEnumTypeTest(t *testing.T, query string) *Result { + result := g(t, Params{ Schema: enumTypeTestSchema, RequestString: query, }) return result } -func executeEnumTypeTestWithParams(t *testing.T, query string, params map[string]interface{}) *types.Result { - result := g(t, graphql.Params{ +func executeEnumTypeTestWithParams(t *testing.T, query string, params map[string]interface{}) *Result { + result := g(t, Params{ Schema: enumTypeTestSchema, RequestString: query, VariableValues: params, @@ -115,47 +111,47 @@ func executeEnumTypeTestWithParams(t *testing.T, query string, params map[string } func TestTypeSystem_EnumValues_AcceptsEnumLiteralsAsInput(t *testing.T) { query := "{ colorInt(fromEnum: GREEN) }" - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "colorInt": 1, }, } result := executeEnumTypeTest(t, query) if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_EnumMayBeOutputType(t *testing.T) { query := "{ colorEnum(fromInt: 1) }" - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "colorEnum": "GREEN", }, } result := executeEnumTypeTest(t, query) if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_EnumMayBeBothInputAndOutputType(t *testing.T) { query := "{ colorEnum(fromEnum: GREEN) }" - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "colorEnum": "GREEN", }, } result := executeEnumTypeTest(t, query) if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_DoesNotAcceptStringLiterals(t *testing.T) { query := `{ colorEnum(fromEnum: "GREEN") }` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Argument "fromEnum" expected type "Color" but got: "GREEN".`, }, }, @@ -163,27 +159,27 @@ func TestTypeSystem_EnumValues_DoesNotAcceptStringLiterals(t *testing.T) { result := executeEnumTypeTest(t, query) t.Skipf("Pending `validator` implementation") if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_DoesNotAcceptIncorrectInternalValue(t *testing.T) { query := `{ colorEnum(fromString: "GREEN") }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "colorEnum": nil, }, } result := executeEnumTypeTest(t, query) if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueInPlaceOfEnumLiteral(t *testing.T) { query := `{ colorEnum(fromEnum: 1) }` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Argument "fromEnum" expected type "Color" but got: 1.`, }, }, @@ -191,16 +187,16 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueInPlaceOfEnumLiteral(t result := executeEnumTypeTest(t, query) t.Skipf("Pending `validator` implementation") if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_DoesNotAcceptEnumLiteralInPlaceOfInt(t *testing.T) { query := `{ colorEnum(fromInt: GREEN) }` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Argument "fromInt" expected type "Int" but got: GREEN.`, }, }, @@ -208,7 +204,7 @@ func TestTypeSystem_EnumValues_DoesNotAcceptEnumLiteralInPlaceOfInt(t *testing.T result := executeEnumTypeTest(t, query) t.Skipf("Pending `validator` implementation") if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -217,14 +213,14 @@ func TestTypeSystem_EnumValues_AcceptsJSONStringAsEnumVariable(t *testing.T) { params := map[string]interface{}{ "color": "BLUE", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "colorEnum": "BLUE", }, } result := executeEnumTypeTestWithParams(t, query, params) if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -233,14 +229,14 @@ func TestTypeSystem_EnumValues_AcceptsEnumLiteralsAsInputArgumentsToMutations(t params := map[string]interface{}{ "color": "GREEN", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "favoriteEnum": "GREEN", }, } result := executeEnumTypeTestWithParams(t, query, params) if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueAsEnumVariable(t *testing.T) { @@ -248,10 +244,10 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueAsEnumVariable(t *testi params := map[string]interface{}{ "color": 2, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$color" expected value of type "Color!" but got: 2.`, }, }, @@ -259,7 +255,7 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueAsEnumVariable(t *testi result := executeEnumTypeTestWithParams(t, query, params) t.Skipf("Pending `validator` implementation") if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_DoesNotAcceptStringVariablesAsEnumInput(t *testing.T) { @@ -267,10 +263,10 @@ func TestTypeSystem_EnumValues_DoesNotAcceptStringVariablesAsEnumInput(t *testin params := map[string]interface{}{ "color": "BLUE", } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$color" of type "String!" used in position expecting type "Color".`, }, }, @@ -278,7 +274,7 @@ func TestTypeSystem_EnumValues_DoesNotAcceptStringVariablesAsEnumInput(t *testin result := executeEnumTypeTestWithParams(t, query, params) t.Skipf("Pending `validator` implementation") if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueVariableAsEnumInput(t *testing.T) { @@ -286,10 +282,10 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueVariableAsEnumInput(t * params := map[string]interface{}{ "color": 2, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$color" of type "Int!" used in position expecting type "Color".`, }, }, @@ -297,7 +293,7 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueVariableAsEnumInput(t * result := executeEnumTypeTestWithParams(t, query, params) t.Skipf("Pending `validator` implementation") if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_EnumValueMayHaveAnInternalValueOfZero(t *testing.T) { @@ -305,7 +301,7 @@ func TestTypeSystem_EnumValues_EnumValueMayHaveAnInternalValueOfZero(t *testing. colorEnum(fromEnum: RED) colorInt(fromEnum: RED) }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "colorEnum": "RED", "colorInt": 0, @@ -313,7 +309,7 @@ func TestTypeSystem_EnumValues_EnumValueMayHaveAnInternalValueOfZero(t *testing. } result := executeEnumTypeTest(t, query) if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestTypeSystem_EnumValues_EnumValueMayBeNullable(t *testing.T) { @@ -321,7 +317,7 @@ func TestTypeSystem_EnumValues_EnumValueMayBeNullable(t *testing.T) { colorEnum colorInt }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "colorEnum": nil, "colorInt": nil, @@ -329,6 +325,6 @@ func TestTypeSystem_EnumValues_EnumValueMayBeNullable(t *testing.T) { } result := executeEnumTypeTest(t, query) if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/errors/graphql.go b/error.go similarity index 65% rename from errors/graphql.go rename to error.go index 31dd64f9..47f2e0cf 100644 --- a/errors/graphql.go +++ b/error.go @@ -1,19 +1,16 @@ -package graphqlerrors +package graphql import ( "fmt" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/language/source" ) type Error struct { Message string Stack string - Nodes []ast.Node - Source *source.Source + Nodes []Node + Source *Source Positions []int - Locations []location.SourceLocation + Locations []SourceLocation } // implements Golang's built-in `error` interface @@ -21,7 +18,7 @@ func (g Error) Error() string { return fmt.Sprintf("%v", g.Message) } -func NewError(message string, nodes []ast.Node, stack string, source *source.Source, positions []int) *Error { +func NewError(message string, nodes []Node, stack string, source *Source, positions []int) *Error { if stack == "" && message != "" { stack = message } @@ -42,9 +39,9 @@ func NewError(message string, nodes []ast.Node, stack string, source *source.Sou positions = append(positions, node.GetLoc().Start) } } - locations := []location.SourceLocation{} + locations := []SourceLocation{} for _, pos := range positions { - loc := location.GetLocation(source, pos) + loc := GetLocation(source, pos) locations = append(locations, loc) } return &Error{ diff --git a/executor/executor.go b/executor.go similarity index 76% rename from executor/executor.go rename to executor.go index 72f6d024..c3fde1cf 100644 --- a/executor/executor.go +++ b/executor.go @@ -1,26 +1,23 @@ -package executor +package graphql import ( "fmt" - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/types" "reflect" "strings" ) type ExecuteParams struct { - Schema types.Schema + Schema Schema Root interface{} - AST *ast.Document + AST *AstDocument OperationName string Args map[string]interface{} } -func Execute(p ExecuteParams, resultChan chan *types.Result) { - var errors []graphqlerrors.FormattedError - var result types.Result +func Execute(p ExecuteParams, resultChan chan *Result) { + var errors []FormattedError + var result Result params := BuildExecutionCtxParams{ Schema: p.Schema, Root: p.Root, @@ -39,9 +36,9 @@ func Execute(p ExecuteParams, resultChan chan *types.Result) { if r := recover(); r != nil { var err error if r, ok := r.(error); ok { - err = graphqlerrors.FormatError(r) + err = FormatError(r) } - exeContext.Errors = append(exeContext.Errors, graphqlerrors.FormatError(err)) + exeContext.Errors = append(exeContext.Errors, FormatError(err)) result.Errors = exeContext.Errors resultChan <- &result } @@ -55,44 +52,44 @@ func Execute(p ExecuteParams, resultChan chan *types.Result) { } type BuildExecutionCtxParams struct { - Schema types.Schema + Schema Schema Root interface{} - AST *ast.Document + AST *AstDocument OperationName string Args map[string]interface{} - Errors []graphqlerrors.FormattedError - Result *types.Result - ResultChan chan *types.Result + Errors []FormattedError + Result *Result + ResultChan chan *Result } type ExecutionContext struct { - Schema types.Schema - Fragments map[string]ast.Definition + Schema Schema + Fragments map[string]Definition Root interface{} - Operation ast.Definition + Operation Definition VariableValues map[string]interface{} - Errors []graphqlerrors.FormattedError + Errors []FormattedError } func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { eCtx := &ExecutionContext{} - operations := map[string]ast.Definition{} - fragments := map[string]ast.Definition{} + operations := map[string]Definition{} + fragments := map[string]Definition{} for _, statement := range p.AST.Definitions { switch stm := statement.(type) { - case *ast.OperationDefinition: + case *AstOperationDefinition: key := "" if stm.GetName() != nil && stm.GetName().Value != "" { key = stm.GetName().Value } operations[key] = stm - case *ast.FragmentDefinition: + case *AstFragmentDefinition: key := "" if stm.GetName() != nil && stm.GetName().Value != "" { key = stm.GetName().Value } fragments[key] = stm default: - err := graphqlerrors.NewFormattedError( + err := NewFormattedError( fmt.Sprintf("GraphQL cannot execute a request containing a %v", statement.GetKind()), ) p.Result.Errors = append(p.Result.Errors, err) @@ -101,7 +98,7 @@ func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { } } if (p.OperationName == "") && (len(operations) != 1) { - err := graphqlerrors.NewFormattedError("Must provide operation name if query contains multiple operations.") + err := NewFormattedError("Must provide operation name if query contains multiple operations.") p.Result.Errors = append(p.Result.Errors, err) p.ResultChan <- p.Result return eCtx @@ -116,14 +113,14 @@ func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { } operation, found := operations[opName] if !found { - err := graphqlerrors.NewFormattedError(fmt.Sprintf(`Unknown operation named "%v".`, opName)) + err := NewFormattedError(fmt.Sprintf(`Unknown operation named "%v".`, opName)) p.Result.Errors = append(p.Result.Errors, err) p.ResultChan <- p.Result return eCtx } variableValues, err := getVariableValues(p.Schema, operation.GetVariableDefinitions(), p.Args) if err != nil { - p.Result.Errors = append(p.Result.Errors, graphqlerrors.FormatError(err)) + p.Result.Errors = append(p.Result.Errors, FormatError(err)) p.ResultChan <- p.Result return eCtx } @@ -140,11 +137,11 @@ func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { type ExecuteOperationParams struct { ExecutionContext *ExecutionContext Root interface{} - Operation ast.Definition + Operation Definition } -func executeOperation(p ExecuteOperationParams, resultChan chan *types.Result) { - var results types.Result +func executeOperation(p ExecuteOperationParams, resultChan chan *Result) { + var results Result operationType := getOperationRootType(p.ExecutionContext.Schema, p.Operation, resultChan) collectFieldsParams := CollectFieldsParams{ @@ -169,10 +166,10 @@ func executeOperation(p ExecuteOperationParams, resultChan chan *types.Result) { } // Extracts the root type of the operation from the schema. -func getOperationRootType(schema types.Schema, operation ast.Definition, r chan *types.Result) (objType *types.Object) { +func getOperationRootType(schema Schema, operation Definition, r chan *Result) (objType *Object) { if operation == nil { - var result types.Result - err := graphqlerrors.NewFormattedError("Can only execute queries and mutations") + var result Result + err := NewFormattedError("Can only execute queries and mutations") result.Errors = append(result.Errors, err) r <- &result return objType @@ -183,16 +180,16 @@ func getOperationRootType(schema types.Schema, operation ast.Definition, r chan case "mutation": mutationType := schema.GetMutationType() if mutationType.Name == "" { - var result types.Result - err := graphqlerrors.NewFormattedError("Schema is not configured for mutations") + var result Result + err := NewFormattedError("Schema is not configured for mutations") result.Errors = append(result.Errors, err) r <- &result return objType } return mutationType default: - var result types.Result - err := graphqlerrors.NewFormattedError("Can only execute queries and mutations") + var result Result + err := NewFormattedError("Can only execute queries and mutations") result.Errors = append(result.Errors, err) r <- &result return objType @@ -201,20 +198,20 @@ func getOperationRootType(schema types.Schema, operation ast.Definition, r chan type ExecuteFieldsParams struct { ExecutionContext *ExecutionContext - ParentType *types.Object + ParentType *Object Source interface{} - Fields map[string][]*ast.Field + Fields map[string][]*AstField } // Implements the "Evaluating selection sets" section of the spec for "write" mode. -func executeFieldsSerially(p ExecuteFieldsParams, resultChan chan *types.Result) { +func executeFieldsSerially(p ExecuteFieldsParams, resultChan chan *Result) { if p.Source == nil { p.Source = map[string]interface{}{} } if p.Fields == nil { - p.Fields = map[string][]*ast.Field{} + p.Fields = map[string][]*AstField{} } - var result types.Result + var result Result finalResults := map[string]interface{}{} for responseName, fieldASTs := range p.Fields { @@ -230,12 +227,12 @@ func executeFieldsSerially(p ExecuteFieldsParams, resultChan chan *types.Result) } // Implements the "Evaluating selection sets" section of the spec for "read" mode. -func executeFields(p ExecuteFieldsParams) (result types.Result) { +func executeFields(p ExecuteFieldsParams) (result Result) { if p.Source == nil { p.Source = map[string]interface{}{} } if p.Fields == nil { - p.Fields = map[string][]*ast.Field{} + p.Fields = map[string][]*AstField{} } finalResults := map[string]interface{}{} for responseName, fieldASTs := range p.Fields { @@ -254,19 +251,19 @@ func executeFields(p ExecuteFieldsParams) (result types.Result) { type CollectFieldsParams struct { ExeContext *ExecutionContext - OperationType *types.Object - SelectionSet *ast.SelectionSet - Fields map[string][]*ast.Field + OperationType *Object + SelectionSet *AstSelectionSet + Fields map[string][]*AstField VisitedFragmentNames map[string]bool } // Given a selectionSet, adds all of the fields in that selection to // the passed in map of fields, and returns it at the end. -func collectFields(p CollectFieldsParams) map[string][]*ast.Field { +func collectFields(p CollectFieldsParams) map[string][]*AstField { fields := p.Fields if fields == nil { - fields = map[string][]*ast.Field{} + fields = map[string][]*AstField{} } if p.VisitedFragmentNames == nil { p.VisitedFragmentNames = map[string]bool{} @@ -276,16 +273,16 @@ func collectFields(p CollectFieldsParams) map[string][]*ast.Field { } for _, iSelection := range p.SelectionSet.Selections { switch selection := iSelection.(type) { - case *ast.Field: + case *AstField: if !shouldIncludeNode(p.ExeContext, selection.Directives) { continue } name := getFieldEntryKey(selection) if _, ok := fields[name]; !ok { - fields[name] = []*ast.Field{} + fields[name] = []*AstField{} } fields[name] = append(fields[name], selection) - case *ast.InlineFragment: + case *AstInlineFragment: if !shouldIncludeNode(p.ExeContext, selection.Directives) || !doesFragmentConditionMatch(p.ExeContext, selection, p.OperationType) { @@ -299,7 +296,7 @@ func collectFields(p CollectFieldsParams) map[string][]*ast.Field { VisitedFragmentNames: p.VisitedFragmentNames, } collectFields(innerParams) - case *ast.FragmentSpread: + case *AstFragmentSpread: fragName := "" if selection.Name != nil { fragName = selection.Name.Value @@ -314,7 +311,7 @@ func collectFields(p CollectFieldsParams) map[string][]*ast.Field { continue } - if fragment, ok := fragment.(*ast.FragmentDefinition); ok { + if fragment, ok := fragment.(*AstFragmentDefinition); ok { if !shouldIncludeNode(p.ExeContext, fragment.Directives) || !doesFragmentConditionMatch(p.ExeContext, fragment, p.OperationType) { continue @@ -335,24 +332,24 @@ func collectFields(p CollectFieldsParams) map[string][]*ast.Field { // Determines if a field should be included based on the @include and @skip // directives, where @skip has higher precedence than @include. -func shouldIncludeNode(eCtx *ExecutionContext, directives []*ast.Directive) bool { +func shouldIncludeNode(eCtx *ExecutionContext, directives []*AstDirective) bool { defaultReturnValue := true - var skipAST *ast.Directive - var includeAST *ast.Directive + var skipAST *AstDirective + var includeAST *AstDirective for _, directive := range directives { if directive == nil || directive.Name == nil { continue } - if directive.Name.Value == types.SkipDirective.Name { + if directive.Name.Value == SkipDirective.Name { skipAST = directive break } } if skipAST != nil { argValues, err := getArgumentValues( - types.SkipDirective.Args, + SkipDirective.Args, skipAST.Arguments, eCtx.VariableValues, ) @@ -370,14 +367,14 @@ func shouldIncludeNode(eCtx *ExecutionContext, directives []*ast.Directive) bool if directive == nil || directive.Name == nil { continue } - if directive.Name.Value == types.IncludeDirective.Name { + if directive.Name.Value == IncludeDirective.Name { includeAST = directive break } } if includeAST != nil { argValues, err := getArgumentValues( - types.IncludeDirective.Args, + IncludeDirective.Args, includeAST.Arguments, eCtx.VariableValues, ) @@ -395,10 +392,10 @@ func shouldIncludeNode(eCtx *ExecutionContext, directives []*ast.Directive) bool } // Determines if a fragment is applicable to the given type. -func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment ast.Node, ttype *types.Object) bool { +func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment Node, ttype *Object) bool { switch fragment := fragment.(type) { - case *ast.FragmentDefinition: + case *AstFragmentDefinition: conditionalType, err := typeFromAST(eCtx.Schema, fragment.TypeCondition) if err != nil { return false @@ -407,10 +404,10 @@ func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment ast.Node, ttype return true } - if conditionalType, ok := conditionalType.(types.Abstract); ok { + if conditionalType, ok := conditionalType.(Abstract); ok { return conditionalType.IsPossibleType(ttype) } - case *ast.InlineFragment: + case *AstInlineFragment: conditionalType, err := typeFromAST(eCtx.Schema, fragment.TypeCondition) if err != nil { return false @@ -419,7 +416,7 @@ func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment ast.Node, ttype return true } - if conditionalType, ok := conditionalType.(types.Abstract); ok { + if conditionalType, ok := conditionalType.(Abstract); ok { return conditionalType.IsPossibleType(ttype) } } @@ -428,7 +425,7 @@ func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment ast.Node, ttype } // Implements the logic to compute the key of a given field’s entry -func getFieldEntryKey(node *ast.Field) string { +func getFieldEntryKey(node *AstField) string { if node.Alias != nil && node.Alias.Value != "" { return node.Alias.Value @@ -450,27 +447,27 @@ type resolveFieldResultState struct { * then calls completeValue to complete promises, serialize scalars, or execute * the sub-selection-set for objects. */ -func resolveField(eCtx *ExecutionContext, parentType *types.Object, source interface{}, fieldASTs []*ast.Field) (result interface{}, resultState resolveFieldResultState) { +func resolveField(eCtx *ExecutionContext, parentType *Object, source interface{}, fieldASTs []*AstField) (result interface{}, resultState resolveFieldResultState) { // catch panic from resolveFn - var returnType types.Output + var returnType Output defer func() (interface{}, resolveFieldResultState) { if r := recover(); r != nil { var err error if r, ok := r.(string); ok { - err = graphqlerrors.NewLocatedError( + err = NewLocatedError( fmt.Sprintf("%v", r), - graphqlerrors.FieldASTsToNodeASTs(fieldASTs), + FieldASTsToNodeASTs(fieldASTs), ) } if r, ok := r.(error); ok { - err = graphqlerrors.FormatError(r) + err = FormatError(r) } // send panic upstream - if _, ok := returnType.(*types.NonNull); ok { - panic(graphqlerrors.FormatError(err)) + if _, ok := returnType.(*NonNull); ok { + panic(FormatError(err)) } - eCtx.Errors = append(eCtx.Errors, graphqlerrors.FormatError(err)) + eCtx.Errors = append(eCtx.Errors, FormatError(err)) return result, resultState } return result, resultState @@ -500,7 +497,7 @@ func resolveField(eCtx *ExecutionContext, parentType *types.Object, source inter // The resolve function's optional third argument is a collection of // information about the current execution state. - info := types.ResolveInfo{ + info := ResolveInfo{ FieldName: fieldName, FieldASTs: fieldASTs, ReturnType: returnType, @@ -516,7 +513,7 @@ func resolveField(eCtx *ExecutionContext, parentType *types.Object, source inter // it is wrapped as a Error with locations. Log this error and return // null if allowed, otherwise throw the error so the parent field can handle // it. - result = resolveFn(types.GQLFRParams{ + result = resolveFn(GQLFRParams{ Source: source, Args: args, Info: info, @@ -526,15 +523,15 @@ func resolveField(eCtx *ExecutionContext, parentType *types.Object, source inter return completed, resultState } -func completeValueCatchingError(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*ast.Field, info types.ResolveInfo, result interface{}) (completed interface{}) { +func completeValueCatchingError(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstField, info ResolveInfo, result interface{}) (completed interface{}) { // catch panic defer func() interface{} { if r := recover(); r != nil { //send panic upstream - if _, ok := returnType.(*types.NonNull); ok { + if _, ok := returnType.(*NonNull); ok { panic(r) } - if err, ok := r.(graphqlerrors.FormattedError); ok { + if err, ok := r.(FormattedError); ok { eCtx.Errors = append(eCtx.Errors, err) } return completed @@ -542,7 +539,7 @@ func completeValueCatchingError(eCtx *ExecutionContext, returnType types.Type, f return completed }() - if returnType, ok := returnType.(*types.NonNull); ok { + if returnType, ok := returnType.(*NonNull); ok { completed := completeValue(eCtx, returnType, fieldASTs, info, result) return completed } @@ -552,13 +549,13 @@ func completeValueCatchingError(eCtx *ExecutionContext, returnType types.Type, f if propertyFn, ok := completed.(func() interface{}); ok { return propertyFn() } - err := graphqlerrors.NewFormattedError("Error resolving func. Expected `func() interface{}` signature") - panic(graphqlerrors.FormatError(err)) + err := NewFormattedError("Error resolving func. Expected `func() interface{}` signature") + panic(FormatError(err)) } return completed } -func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*ast.Field, info types.ResolveInfo, result interface{}) interface{} { +func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstField, info ResolveInfo, result interface{}) interface{} { // TODO: explore resolving go-routines in completeValue @@ -567,18 +564,18 @@ func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*a if propertyFn, ok := result.(func() interface{}); ok { return propertyFn() } - err := graphqlerrors.NewFormattedError("Error resolving func. Expected `func() interface{}` signature") - panic(graphqlerrors.FormatError(err)) + err := NewFormattedError("Error resolving func. Expected `func() interface{}` signature") + panic(FormatError(err)) } - if returnType, ok := returnType.(*types.NonNull); ok { + if returnType, ok := returnType.(*NonNull); ok { completed := completeValue(eCtx, returnType.OfType, fieldASTs, info, result) if completed == nil { - err := graphqlerrors.NewLocatedError( + err := NewLocatedError( fmt.Sprintf("Cannot return null for non-nullable field %v.%v.", info.ParentType, info.FieldName), - graphqlerrors.FieldASTsToNodeASTs(fieldASTs), + FieldASTsToNodeASTs(fieldASTs), ) - panic(graphqlerrors.FormatError(err)) + panic(FormatError(err)) } return completed } @@ -588,7 +585,7 @@ func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*a } // If field type is List, complete each item in the list with the inner type - if returnType, ok := returnType.(*types.List); ok { + if returnType, ok := returnType.(*List); ok { resultVal := reflect.ValueOf(result) err := invariant( @@ -596,7 +593,7 @@ func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*a "User Error: expected iterable, but did not find one.", ) if err != nil { - panic(graphqlerrors.FormatError(err)) + panic(FormatError(err)) } itemType := returnType.OfType @@ -611,10 +608,10 @@ func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*a // If field type is Scalar or Enum, serialize to a valid value, returning // null if serialization is not possible. - if returnType, ok := returnType.(*types.Scalar); ok { + if returnType, ok := returnType.(*Scalar); ok { err := invariant(returnType.Serialize != nil, "Missing serialize method on type") if err != nil { - panic(graphqlerrors.FormatError(err)) + panic(FormatError(err)) } serializedResult := returnType.Serialize(result) if isNullish(serializedResult) { @@ -622,10 +619,10 @@ func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*a } return serializedResult } - if returnType, ok := returnType.(*types.Enum); ok { + if returnType, ok := returnType.(*Enum); ok { err := invariant(returnType.Serialize != nil, "Missing serialize method on type") if err != nil { - panic(graphqlerrors.FormatError(err)) + panic(FormatError(err)) } serializedResult := returnType.Serialize(result) if isNullish(serializedResult) { @@ -634,15 +631,15 @@ func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*a return serializedResult } - // Field type must be Object, Interface or Union and expect sub-selections. - var objectType *types.Object + // AstField type must be Object, Interface or Union and expect sub-selections. + var objectType *Object switch returnType := returnType.(type) { - case *types.Object: + case *Object: objectType = returnType - case types.Abstract: + case Abstract: objectType = returnType.GetObjectType(result, info) if objectType != nil && !returnType.IsPossibleType(objectType) { - panic(graphqlerrors.NewFormattedError( + panic(NewFormattedError( fmt.Sprintf(`Runtime Object type "%v" is not a possible type `+ `for "%v".`, objectType, returnType), )) @@ -656,13 +653,13 @@ func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*a // current result. If isTypeOf returns false, then raise an error rather // than continuing execution. if objectType.IsTypeOf != nil && !objectType.IsTypeOf(result, info) { - panic(graphqlerrors.NewFormattedError( + panic(NewFormattedError( fmt.Sprintf(`Expected value of type "%v" but got: %T.`, objectType, result), )) } // Collect sub-fields to execute to complete this value. - subFieldASTs := map[string][]*ast.Field{} + subFieldASTs := map[string][]*AstField{} visitedFragmentNames := map[string]bool{} for _, fieldAST := range fieldASTs { if fieldAST == nil { @@ -692,7 +689,7 @@ func completeValue(eCtx *ExecutionContext, returnType types.Type, fieldASTs []*a } -func defaultResolveFn(p types.GQLFRParams) interface{} { +func defaultResolveFn(p GQLFRParams) interface{} { // try to resolve p.Source as a struct first sourceVal := reflect.ValueOf(p.Source) if sourceVal.IsValid() && sourceVal.Type().Kind() == reflect.Ptr { @@ -754,22 +751,22 @@ func defaultResolveFn(p types.GQLFRParams) interface{} { * added to the query type, but that would require mutating type * definitions, which would cause issues. */ -func getFieldDef(schema types.Schema, parentType *types.Object, fieldName string) *types.FieldDefinition { +func getFieldDef(schema Schema, parentType *Object, fieldName string) *FieldDefinition { if parentType == nil { return nil } - if fieldName == types.SchemaMetaFieldDef.Name && + if fieldName == SchemaMetaFieldDef.Name && schema.GetQueryType() == parentType { - return types.SchemaMetaFieldDef + return SchemaMetaFieldDef } - if fieldName == types.TypeMetaFieldDef.Name && + if fieldName == TypeMetaFieldDef.Name && schema.GetQueryType() == parentType { - return types.TypeMetaFieldDef + return TypeMetaFieldDef } - if fieldName == types.TypeNameMetaFieldDef.Name { - return types.TypeNameMetaFieldDef + if fieldName == TypeNameMetaFieldDef.Name { + return TypeNameMetaFieldDef } return parentType.GetFields()[fieldName] } diff --git a/executor/executor_schema_test.go b/executor_schema_test.go similarity index 71% rename from executor/executor_schema_test.go rename to executor_schema_test.go index 9aa78e36..9f4932a2 100644 --- a/executor/executor_schema_test.go +++ b/executor_schema_test.go @@ -1,10 +1,7 @@ -package executor_test +package graphql import ( "fmt" - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) @@ -73,40 +70,40 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { RecentArticle: article("1"), } - blogImage := types.NewObject(types.ObjectConfig{ + blogImage := NewObject(ObjectConfig{ Name: "Image", - Fields: types.FieldConfigMap{ - "url": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "url": &FieldConfig{ + Type: String, }, - "width": &types.FieldConfig{ - Type: types.Int, + "width": &FieldConfig{ + Type: Int, }, - "height": &types.FieldConfig{ - Type: types.Int, + "height": &FieldConfig{ + Type: Int, }, }, }) - blogAuthor := types.NewObject(types.ObjectConfig{ + blogAuthor := NewObject(ObjectConfig{ Name: "Author", - Fields: types.FieldConfigMap{ - "id": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "id": &FieldConfig{ + Type: String, }, - "name": &types.FieldConfig{ - Type: types.String, + "name": &FieldConfig{ + Type: String, }, - "pic": &types.FieldConfig{ + "pic": &FieldConfig{ Type: blogImage, - Args: types.FieldConfigArgument{ - "width": &types.ArgumentConfig{ - Type: types.Int, + Args: FieldConfigArgument{ + "width": &ArgumentConfig{ + Type: Int, }, - "height": &types.ArgumentConfig{ - Type: types.Int, + "height": &ArgumentConfig{ + Type: Int, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if author, ok := p.Source.(*testAuthor); ok { width := fmt.Sprintf("%v", p.Args["width"]) height := fmt.Sprintf("%v", p.Args["height"]) @@ -115,55 +112,55 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { return nil }, }, - "recentArticle": &types.FieldConfig{}, + "recentArticle": &FieldConfig{}, }, }) - blogArticle := types.NewObject(types.ObjectConfig{ + blogArticle := NewObject(ObjectConfig{ Name: "Article", - Fields: types.FieldConfigMap{ - "id": &types.FieldConfig{ - Type: types.NewNonNull(types.String), + Fields: FieldConfigMap{ + "id": &FieldConfig{ + Type: NewNonNull(String), }, - "isPublished": &types.FieldConfig{ - Type: types.Boolean, + "isPublished": &FieldConfig{ + Type: Boolean, }, - "author": &types.FieldConfig{ + "author": &FieldConfig{ Type: blogAuthor, }, - "title": &types.FieldConfig{ - Type: types.String, + "title": &FieldConfig{ + Type: String, }, - "body": &types.FieldConfig{ - Type: types.String, + "body": &FieldConfig{ + Type: String, }, - "keywords": &types.FieldConfig{ - Type: types.NewList(types.String), + "keywords": &FieldConfig{ + Type: NewList(String), }, }, }) - blogAuthor.AddFieldConfig("recentArticle", &types.FieldConfig{ + blogAuthor.AddFieldConfig("recentArticle", &FieldConfig{ Type: blogArticle, }) - blogQuery := types.NewObject(types.ObjectConfig{ + blogQuery := NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "article": &types.FieldConfig{ + Fields: FieldConfigMap{ + "article": &FieldConfig{ Type: blogArticle, - Args: types.FieldConfigArgument{ - "id": &types.ArgumentConfig{ - Type: types.ID, + Args: FieldConfigArgument{ + "id": &ArgumentConfig{ + Type: ID, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { id := p.Args["id"] return article(id) }, }, - "feed": &types.FieldConfig{ - Type: types.NewList(blogArticle), - Resolve: func(p types.GQLFRParams) interface{} { + "feed": &FieldConfig{ + Type: NewList(blogArticle), + Resolve: func(p GQLFRParams) interface{} { return []*testArticle{ article(1), article(2), @@ -181,7 +178,7 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { }, }) - blogSchema, err := types.NewSchema(types.SchemaConfig{ + blogSchema, err := NewSchema(SchemaConfig{ Query: blogQuery, }) if err != nil { @@ -222,7 +219,7 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "article": map[string]interface{}{ "title": "My Article 1", @@ -298,18 +295,18 @@ func TestExecutesUsingAComplexSchema(t *testing.T) { } // parse query - ast := testutil.Parse(t, request) + ast := TestParse(t, request) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: blogSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/executor/executor_test.go b/executor_test.go similarity index 59% rename from executor/executor_test.go rename to executor_test.go index aedb98d8..ccc482a7 100644 --- a/executor/executor_test.go +++ b/executor_test.go @@ -1,13 +1,8 @@ -package executor_test +package graphql import ( "encoding/json" "fmt" - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) @@ -67,7 +62,7 @@ func TestExecutesArbitraryCode(t *testing.T) { } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "b": "Banana", "x": "Cookie", @@ -103,7 +98,7 @@ func TestExecutesArbitraryCode(t *testing.T) { } // Schema Definitions - picResolverFn := func(p types.GQLFRParams) interface{} { + picResolverFn := func(p GQLFRParams) interface{} { // get and type assert ResolveFn for this field picResolver, ok := p.Source.(map[string]interface{})["pic"].(func(size int) string) if !ok { @@ -116,67 +111,67 @@ func TestExecutesArbitraryCode(t *testing.T) { } return picResolver(sizeArg) } - dataType := types.NewObject(types.ObjectConfig{ + dataType := NewObject(ObjectConfig{ Name: "DataType", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, - "b": &types.FieldConfig{ - Type: types.String, + "b": &FieldConfig{ + Type: String, }, - "c": &types.FieldConfig{ - Type: types.String, + "c": &FieldConfig{ + Type: String, }, - "d": &types.FieldConfig{ - Type: types.String, + "d": &FieldConfig{ + Type: String, }, - "e": &types.FieldConfig{ - Type: types.String, + "e": &FieldConfig{ + Type: String, }, - "f": &types.FieldConfig{ - Type: types.String, + "f": &FieldConfig{ + Type: String, }, - "pic": &types.FieldConfig{ - Args: types.FieldConfigArgument{ - "size": &types.ArgumentConfig{ - Type: types.Int, + "pic": &FieldConfig{ + Args: FieldConfigArgument{ + "size": &ArgumentConfig{ + Type: Int, }, }, - Type: types.String, + Type: String, Resolve: picResolverFn, }, }, }) - deepDataType := types.NewObject(types.ObjectConfig{ + deepDataType := NewObject(ObjectConfig{ Name: "DeepDataType", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, - "b": &types.FieldConfig{ - Type: types.String, + "b": &FieldConfig{ + Type: String, }, - "c": &types.FieldConfig{ - Type: types.NewList(types.String), + "c": &FieldConfig{ + Type: NewList(String), }, - "deeper": &types.FieldConfig{ - Type: types.NewList(dataType), + "deeper": &FieldConfig{ + Type: NewList(dataType), }, }, }) // Exploring a way to have a Object within itself // in this case DataType has DeepDataType has DataType - dataType.AddFieldConfig("deep", &types.FieldConfig{ + dataType.AddFieldConfig("deep", &FieldConfig{ Type: deepDataType, }) // in this case DataType has DataType - dataType.AddFieldConfig("promise", &types.FieldConfig{ + dataType.AddFieldConfig("promise", &FieldConfig{ Type: dataType, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: dataType, }) if err != nil { @@ -184,26 +179,26 @@ func TestExecutesArbitraryCode(t *testing.T) { } // parse query - astDoc := testutil.Parse(t, query) + astDoc := TestParse(t, query) // execute args := map[string]interface{}{ "size": 100, } operationName := "Example" - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, Root: data, AST: astDoc, OperationName: operationName, Args: args, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -223,7 +218,7 @@ func TestMergesParallelFragments(t *testing.T) { } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "Apple", "b": "Banana", @@ -239,38 +234,38 @@ func TestMergesParallelFragments(t *testing.T) { }, } - typeObjectType := types.NewObject(types.ObjectConfig{ + typeObjectType := NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { return "Apple" }, }, - "b": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + "b": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { return "Banana" }, }, - "c": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + "c": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { return "Cherry" }, }, }, }) - deepTypeFieldConfig := &types.FieldConfig{ + deepTypeFieldConfig := &FieldConfig{ Type: typeObjectType, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { return p.Source }, } typeObjectType.AddFieldConfig("deep", deepTypeFieldConfig) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: typeObjectType, }) if err != nil { @@ -278,19 +273,19 @@ func TestMergesParallelFragments(t *testing.T) { } // parse query - ast := testutil.Parse(t, query) + ast := TestParse(t, query) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -306,13 +301,13 @@ func TestThreadsContextCorrectly(t *testing.T) { var resolvedContext map[string]interface{} - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { resolvedContext = p.Source.(map[string]interface{}) return resolvedContext }, @@ -325,15 +320,15 @@ func TestThreadsContextCorrectly(t *testing.T) { } // parse query - ast := testutil.Parse(t, query) + ast := TestParse(t, query) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, Root: data, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } @@ -354,21 +349,21 @@ func TestCorrectlyThreadsArguments(t *testing.T) { var resolvedArgs map[string]interface{} - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "b": &types.FieldConfig{ - Args: types.FieldConfigArgument{ - "numArg": &types.ArgumentConfig{ - Type: types.Int, + Fields: FieldConfigMap{ + "b": &FieldConfig{ + Args: FieldConfigArgument{ + "numArg": &ArgumentConfig{ + Type: Int, }, - "stringArg": &types.ArgumentConfig{ - Type: types.String, + "stringArg": &ArgumentConfig{ + Type: String, }, }, - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Type: String, + Resolve: func(p GQLFRParams) interface{} { resolvedArgs = p.Args return resolvedArgs }, @@ -381,14 +376,14 @@ func TestCorrectlyThreadsArguments(t *testing.T) { } // parse query - ast := testutil.Parse(t, query) + ast := TestParse(t, query) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } @@ -415,11 +410,11 @@ func TestNullsOutErrorSubtrees(t *testing.T) { "sync": "sync", "syncError": nil, } - expectedErrors := []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + expectedErrors := []FormattedError{ + FormattedError{ Message: "Error getting syncError", - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 3, Column: 7, }, }, @@ -434,15 +429,15 @@ func TestNullsOutErrorSubtrees(t *testing.T) { panic("Error getting syncError") }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "sync": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "sync": &FieldConfig{ + Type: String, }, - "syncError": &types.FieldConfig{ - Type: types.String, + "syncError": &FieldConfig{ + Type: String, }, }, }), @@ -452,23 +447,23 @@ func TestNullsOutErrorSubtrees(t *testing.T) { } // parse query - ast := testutil.Parse(t, query) + ast := TestParse(t, query) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) == 0 { t.Fatalf("wrong result, expected errors, got %v", len(result.Errors)) } if !reflect.DeepEqual(expectedData, result.Data) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedData, result.Data)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expectedData, result.Data)) } if !reflect.DeepEqual(expectedErrors, result.Errors) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedErrors, result.Errors)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expectedErrors, result.Errors)) } } @@ -479,18 +474,18 @@ func TestUsesTheInlineOperationIfNoOperationIsProvided(t *testing.T) { "a": "b", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "b", }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, }, }), @@ -500,20 +495,20 @@ func TestUsesTheInlineOperationIfNoOperationIsProvided(t *testing.T) { } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -524,18 +519,18 @@ func TestUsesTheOnlyOperationIfNoOperationIsProvided(t *testing.T) { "a": "b", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "b", }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, }, }), @@ -545,20 +540,20 @@ func TestUsesTheOnlyOperationIfNoOperationIsProvided(t *testing.T) { } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -569,19 +564,19 @@ func TestThrowsIfNoOperationIsProvidedWithMultipleOperations(t *testing.T) { "a": "b", } - expectedErrors := []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + expectedErrors := []FormattedError{ + FormattedError{ Message: "Must provide operation name if query contains multiple operations.", - Locations: []location.SourceLocation{}, + Locations: []SourceLocation{}, }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, }, }), @@ -591,15 +586,15 @@ func TestThrowsIfNoOperationIsProvidedWithMultipleOperations(t *testing.T) { } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != 1 { t.Fatalf("wrong result, expected len(1) unexpected len: %v", len(result.Errors)) } @@ -607,7 +602,7 @@ func TestThrowsIfNoOperationIsProvidedWithMultipleOperations(t *testing.T) { t.Fatalf("wrong result, expected nil result.Data, got %v", result.Data) } if !reflect.DeepEqual(expectedErrors, result.Errors) { - t.Fatalf("unexpected result, Diff: %v", testutil.Diff(expectedErrors, result.Errors)) + t.Fatalf("unexpected result, Diff: %v", Diff(expectedErrors, result.Errors)) } } @@ -619,26 +614,26 @@ func TestUsesTheQuerySchemaForQueries(t *testing.T) { "c": "d", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "b", }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Q", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, }, }), - Mutation: types.NewObject(types.ObjectConfig{ + Mutation: NewObject(ObjectConfig{ Name: "M", - Fields: types.FieldConfigMap{ - "c": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "c": &FieldConfig{ + Type: String, }, }, }), @@ -648,21 +643,21 @@ func TestUsesTheQuerySchemaForQueries(t *testing.T) { } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, OperationName: "Q", } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -674,26 +669,26 @@ func TestUsesTheMutationSchemaForQueries(t *testing.T) { "c": "d", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "c": "d", }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Q", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, }, }), - Mutation: types.NewObject(types.ObjectConfig{ + Mutation: NewObject(ObjectConfig{ Name: "M", - Fields: types.FieldConfigMap{ - "c": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "c": &FieldConfig{ + Type: String, }, }, }), @@ -703,21 +698,21 @@ func TestUsesTheMutationSchemaForQueries(t *testing.T) { } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, OperationName: "M", } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -740,7 +735,7 @@ func TestCorrectFieldOrderingDespiteExecutionOrder(t *testing.T) { "e": func() interface{} { return "e" }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "a", "b": "b", @@ -750,24 +745,24 @@ func TestCorrectFieldOrderingDespiteExecutionOrder(t *testing.T) { }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, - "b": &types.FieldConfig{ - Type: types.String, + "b": &FieldConfig{ + Type: String, }, - "c": &types.FieldConfig{ - Type: types.String, + "c": &FieldConfig{ + Type: String, }, - "d": &types.FieldConfig{ - Type: types.String, + "d": &FieldConfig{ + Type: String, }, - "e": &types.FieldConfig{ - Type: types.String, + "e": &FieldConfig{ + Type: String, }, }, }), @@ -777,20 +772,20 @@ func TestCorrectFieldOrderingDespiteExecutionOrder(t *testing.T) { } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } // TODO: test to ensure key ordering @@ -822,18 +817,18 @@ func TestAvoidsRecursion(t *testing.T) { "a": "b", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "a": "b", }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, }, }), @@ -843,21 +838,21 @@ func TestAvoidsRecursion(t *testing.T) { } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, OperationName: "Q", } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -868,24 +863,24 @@ func TestDoesNotIncludeIllegalFieldsInOutput(t *testing.T) { thisIsIllegalDontIncludeMe }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{}, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Q", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "a": &FieldConfig{ + Type: String, }, }, }), - Mutation: types.NewObject(types.ObjectConfig{ + Mutation: NewObject(ObjectConfig{ Name: "M", - Fields: types.FieldConfigMap{ - "c": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "c": &FieldConfig{ + Type: String, }, }, }), @@ -895,19 +890,19 @@ func TestDoesNotIncludeIllegalFieldsInOutput(t *testing.T) { } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != 0 { t.Fatalf("wrong result, expected len(%v) errors, got len(%v)", len(expected.Errors), len(result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -915,36 +910,36 @@ func TestDoesNotIncludeArgumentsThatWereNotSet(t *testing.T) { doc := `{ field(a: true, c: false, e: 0) }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "field": `{"a":true,"c":false,"e":0}`, }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Type", - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "a": &types.ArgumentConfig{ - Type: types.Boolean, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "a": &ArgumentConfig{ + Type: Boolean, }, - "b": &types.ArgumentConfig{ - Type: types.Boolean, + "b": &ArgumentConfig{ + Type: Boolean, }, - "c": &types.ArgumentConfig{ - Type: types.Boolean, + "c": &ArgumentConfig{ + Type: Boolean, }, - "d": &types.ArgumentConfig{ - Type: types.Int, + "d": &ArgumentConfig{ + Type: Int, }, - "e": &types.ArgumentConfig{ - Type: types.Int, + "e": &ArgumentConfig{ + Type: Int, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { args, _ := json.Marshal(p.Args) return string(args) }, @@ -957,19 +952,19 @@ func TestDoesNotIncludeArgumentsThatWereNotSet(t *testing.T) { } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -991,7 +986,7 @@ func TestFailsWhenAnIsTypeOfCheckIsNotMet(t *testing.T) { }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "specials": []interface{}{ map[string]interface{}{ @@ -1000,38 +995,38 @@ func TestFailsWhenAnIsTypeOfCheckIsNotMet(t *testing.T) { nil, }, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ - Message: `Expected value of type "SpecialType" but got: executor_test.testNotSpecialType.`, - Locations: []location.SourceLocation{}, + Errors: []FormattedError{ + FormattedError{ + Message: `Expected value of type "SpecialType" but got: graphql.testNotSpecialType.`, + Locations: []SourceLocation{}, }, }, } - specialType := types.NewObject(types.ObjectConfig{ + specialType := NewObject(ObjectConfig{ Name: "SpecialType", - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { if _, ok := value.(testSpecialType); ok { return true } return false }, - Fields: types.FieldConfigMap{ - "value": &types.FieldConfig{ - Type: types.String, - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "value": &FieldConfig{ + Type: String, + Resolve: func(p GQLFRParams) interface{} { return p.Source.(testSpecialType).Value }, }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "specials": &types.FieldConfig{ - Type: types.NewList(specialType), - Resolve: func(p types.GQLFRParams) interface{} { + Fields: FieldConfigMap{ + "specials": &FieldConfig{ + Type: NewList(specialType), + Resolve: func(p GQLFRParams) interface{} { return p.Source.(map[string]interface{})["specials"] }, }, @@ -1043,20 +1038,20 @@ func TestFailsWhenAnIsTypeOfCheckIsNotMet(t *testing.T) { } // parse query - ast := testutil.Parse(t, query) + ast := TestParse(t, query) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) == 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -1067,22 +1062,22 @@ func TestFailsToExecuteQueryContainingATypeDefinition(t *testing.T) { type Query { foo: String } ` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: "GraphQL cannot execute a request containing a ObjectDefinition", - Locations: []location.SourceLocation{}, + Locations: []SourceLocation{}, }, }, } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "foo": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "foo": &FieldConfig{ + Type: String, }, }, }), @@ -1092,18 +1087,18 @@ func TestFailsToExecuteQueryContainingATypeDefinition(t *testing.T) { } // parse query - ast := testutil.Parse(t, query) + ast := TestParse(t, query) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != 1 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/errors/formatted.go b/formatted.go similarity index 84% rename from errors/formatted.go rename to formatted.go index d12b5a02..25b3697c 100644 --- a/errors/formatted.go +++ b/formatted.go @@ -1,13 +1,12 @@ -package graphqlerrors +package graphql import ( "errors" - "github.com/chris-ramon/graphql/language/location" ) type FormattedError struct { Message string - Locations []location.SourceLocation + Locations []SourceLocation } func (g FormattedError) Error() string { @@ -36,7 +35,7 @@ func FormatError(err error) FormattedError { default: return FormattedError{ Message: err.Error(), - Locations: []location.SourceLocation{}, + Locations: []SourceLocation{}, } } } diff --git a/graphql.go b/graphql.go index 694f9eba..4be0be75 100644 --- a/graphql.go +++ b/graphql.go @@ -1,52 +1,43 @@ package graphql -import ( - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/language/parser" - "github.com/chris-ramon/graphql/language/source" - "github.com/chris-ramon/graphql/types" - "github.com/chris-ramon/graphql/validator" -) - type Params struct { - Schema types.Schema + Schema Schema RequestString string RootObject map[string]interface{} VariableValues map[string]interface{} OperationName string } -func Graphql(p Params, resultChannel chan *types.Result) { - source := source.NewSource(&source.Source{ +func Graphql(p Params, resultChannel chan *Result) { + source := NewSource(&Source{ Body: p.RequestString, Name: "GraphQL request", }) - AST, err := parser.Parse(parser.ParseParams{Source: source}) + AST, err := Parse(ParseParams{Source: source}) if err != nil { - result := types.Result{ - Errors: graphqlerrors.FormatErrors(err), + result := Result{ + Errors: FormatErrors(err), } resultChannel <- &result return } - validationResult := validator.ValidateDocument(p.Schema, AST) + validationResult := ValidateDocument(p.Schema, AST) if !validationResult.IsValid { - result := types.Result{ + result := Result{ Errors: validationResult.Errors, } resultChannel <- &result return } else { - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: p.Schema, Root: p.RootObject, AST: AST, OperationName: p.OperationName, Args: p.VariableValues, } - executor.Execute(ep, resultChannel) + Execute(ep, resultChannel) return } } diff --git a/graphql_test.go b/graphql_test.go index aa1b42f0..7fb4839e 100644 --- a/graphql_test.go +++ b/graphql_test.go @@ -3,15 +3,11 @@ package graphql import ( "reflect" "testing" - - "github.com/chris-ramon/graphql/types" - - "./testutil" ) type T struct { Query string - Schema types.Schema + Schema Schema Expected interface{} } @@ -25,8 +21,8 @@ var ( } } `, - Schema: testutil.StarWarsSchema, - Expected: &types.Result{ + Schema: StarWarsSchema, + Expected: &Result{ Data: map[string]interface{}{ "hero": map[string]interface{}{ "name": "R2-D2", @@ -46,8 +42,8 @@ var ( } } `, - Schema: testutil.StarWarsSchema, - Expected: &types.Result{ + Schema: StarWarsSchema, + Expected: &Result{ Data: map[string]interface{}{ "hero": map[string]interface{}{ "id": "2001", @@ -81,31 +77,31 @@ func TestQuery(t *testing.T) { } func testGraphql(test T, p Params, t *testing.T) { - resultChannel := make(chan *types.Result) + resultChannel := make(chan *Result) go Graphql(p, resultChannel) result := <-resultChannel if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(result, test.Expected) { - t.Fatalf("wrong result, query: %v, graphql result diff: %v", test.Query, testutil.Diff(test.Expected, result)) + t.Fatalf("wrong result, query: %v, graphql result diff: %v", test.Query, Diff(test.Expected, result)) } } func TestBasicGraphQLExample(t *testing.T) { // taken from `graphql-js` README - helloFieldResolved := func(p types.GQLFRParams) interface{} { + helloFieldResolved := func(p GQLFRParams) interface{} { return "world" } - schema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + schema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "RootQueryType", - Fields: types.FieldConfigMap{ - "hello": &types.FieldConfig{ + Fields: FieldConfigMap{ + "hello": &FieldConfig{ Description: "Returns `world`", - Type: types.String, + Type: String, Resolve: helloFieldResolved, }, }, @@ -120,7 +116,7 @@ func TestBasicGraphQLExample(t *testing.T) { "hello": "world", } - resultChannel := make(chan *types.Result) + resultChannel := make(chan *Result) go Graphql(Params{ Schema: schema, RequestString: query, @@ -130,7 +126,7 @@ func TestBasicGraphQLExample(t *testing.T) { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(result.Data, expected) { - t.Fatalf("wrong result, query: %v, graphql result diff: %v", query, testutil.Diff(expected, result)) + t.Fatalf("wrong result, query: %v, graphql result diff: %v", query, Diff(expected, result)) } } diff --git a/types/introspection.go b/introspection.go similarity index 91% rename from types/introspection.go rename to introspection.go index 4ff88d4b..807da787 100644 --- a/types/introspection.go +++ b/introspection.go @@ -1,10 +1,7 @@ -package types +package graphql import ( "fmt" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/printer" - "math" "reflect" ) @@ -143,14 +140,14 @@ func init() { return nil } astVal := astFromValue(inputVal.DefaultValue, inputVal) - return printer.Print(astVal) + return Print(astVal) } if inputVal, ok := p.Source.(*InputObjectField); ok { if inputVal.DefaultValue == nil { return nil } astVal := astFromValue(inputVal.DefaultValue, inputVal) - return printer.Print(astVal) + return Print(astVal) } return nil }, @@ -473,7 +470,7 @@ mutation operations.`, * | Number | Int / Float | * */ -func astFromValue(value interface{}, ttype Type) ast.Value { +func astFromValue(value interface{}, ttype Type) Value { if ttype, ok := ttype.(*NonNull); ok { // Note: we're not checking that the result is non-null. @@ -500,7 +497,7 @@ func astFromValue(value interface{}, ttype Type) ast.Value { if ttype, ok := ttype.(*List); ok { if valueVal.Type().Kind() == reflect.Slice { itemType := ttype.OfType - values := []ast.Value{} + values := []Value{} for i := 0; i < valueVal.Len(); i++ { item := valueVal.Index(i).Interface() itemAST := astFromValue(item, itemType) @@ -508,7 +505,7 @@ func astFromValue(value interface{}, ttype Type) ast.Value { values = append(values, itemAST) } } - return ast.NewListValue(&ast.ListValue{ + return NewAstListValue(&AstListValue{ Values: values, }) } else { @@ -521,66 +518,48 @@ func astFromValue(value interface{}, ttype Type) ast.Value { } if valueVal.Type().Kind() == reflect.Map { - // TODO: implement astFromValue from Map to ast.Value + // TODO: implement astFromValue from Map to Value } if value, ok := value.(bool); ok { - return ast.NewBooleanValue(&ast.BooleanValue{ + return NewAstBooleanValue(&AstBooleanValue{ Value: value, }) } if value, ok := value.(int); ok { if ttype == Float { - return ast.NewIntValue(&ast.IntValue{ + return NewAstIntValue(&AstIntValue{ Value: fmt.Sprintf("%v.0", value), }) } - return ast.NewIntValue(&ast.IntValue{ + return NewAstIntValue(&AstIntValue{ Value: fmt.Sprintf("%v", value), }) } if value, ok := value.(float32); ok { - return ast.NewFloatValue(&ast.FloatValue{ + return NewAstFloatValue(&AstFloatValue{ Value: fmt.Sprintf("%v", value), }) } if value, ok := value.(float64); ok { - return ast.NewFloatValue(&ast.FloatValue{ + return NewAstFloatValue(&AstFloatValue{ Value: fmt.Sprintf("%v", value), }) } if value, ok := value.(string); ok { if _, ok := ttype.(*Enum); ok { - return ast.NewEnumValue(&ast.EnumValue{ + return NewAstEnumValue(&AstEnumValue{ Value: fmt.Sprintf("%v", value), }) } - return ast.NewStringValue(&ast.StringValue{ + return NewAstStringValue(&AstStringValue{ Value: fmt.Sprintf("%v", value), }) } // fallback, treat as string - return ast.NewStringValue(&ast.StringValue{ + return NewAstStringValue(&AstStringValue{ Value: fmt.Sprintf("%v", value), }) } - -// Returns true if a value is null, undefined, or NaN. -// TODO: move isNullish to utilities. This is a copy of isNullish in `executor` -func isNullish(value interface{}) bool { - if value, ok := value.(string); ok { - return value == "" - } - if value, ok := value.(int); ok { - return math.IsNaN(float64(value)) - } - if value, ok := value.(float32); ok { - return math.IsNaN(float64(value)) - } - if value, ok := value.(float64); ok { - return math.IsNaN(value) - } - return value == nil -} diff --git a/testutil/introspection_query.go b/introspection_query.go similarity index 98% rename from testutil/introspection_query.go rename to introspection_query.go index 9d336353..2509a343 100644 --- a/testutil/introspection_query.go +++ b/introspection_query.go @@ -1,4 +1,4 @@ -package testutil +package graphql var IntrospectionQuery = ` query IntrospectionQuery { diff --git a/types/introspection_test.go b/introspection_test.go similarity index 84% rename from types/introspection_test.go rename to introspection_test.go index 629e487c..83670e48 100644 --- a/types/introspection_test.go +++ b/introspection_test.go @@ -1,29 +1,24 @@ -package types_test +package graphql import ( - "github.com/chris-ramon/graphql" - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) -func g(t *testing.T, p graphql.Params) *types.Result { - resultChannel := make(chan *types.Result) - go graphql.Graphql(p, resultChannel) +func g(t *testing.T, p Params) *Result { + resultChannel := make(chan *Result) + go Graphql(p, resultChannel) result := <-resultChannel return result } func TestIntrospection_ExecutesAnIntrospectionQuery(t *testing.T) { - emptySchema, err := types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + emptySchema, err := NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "QueryRoot", - Fields: types.FieldConfigMap{ - "onlyField": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "onlyField": &FieldConfig{ + Type: String, }, }, }), @@ -738,46 +733,46 @@ func TestIntrospection_ExecutesAnIntrospectionQuery(t *testing.T) { }, }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: emptySchema, - RequestString: testutil.IntrospectionQuery, + RequestString: IntrospectionQuery, }) - if !testutil.ContainSubset(result.Data.(map[string]interface{}), expectedDataSubSet) { + if !ContainSubset(result.Data.(map[string]interface{}), expectedDataSubSet) { t.Fatalf("unexpected, result does not contain subset of expected data") } } func TestIntrospection_ExecutesAnInputObject(t *testing.T) { - testInputObject := types.NewInputObject(types.InputObjectConfig{ + testInputObject := NewInputObject(InputObjectConfig{ Name: "TestInputObject", - Fields: types.InputObjectConfigFieldMap{ - "a": &types.InputObjectFieldConfig{ - Type: types.String, + Fields: InputObjectConfigFieldMap{ + "a": &InputObjectFieldConfig{ + Type: String, DefaultValue: "foo", }, - "b": &types.InputObjectFieldConfig{ - Type: types.NewList(types.String), + "b": &InputObjectFieldConfig{ + Type: NewList(String), }, }, }) - testType := types.NewObject(types.ObjectConfig{ + testType := NewObject(ObjectConfig{ Name: "TestType", - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "complex": &types.ArgumentConfig{ + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "complex": &ArgumentConfig{ Type: testInputObject, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { return p.Args["complex"] }, }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: testType, }) if err != nil { @@ -850,26 +845,26 @@ func TestIntrospection_ExecutesAnInputObject(t *testing.T) { }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: schema, RequestString: query, }) - if !testutil.ContainSubset(result.Data.(map[string]interface{}), expectedDataSubSet) { + if !ContainSubset(result.Data.(map[string]interface{}), expectedDataSubSet) { t.Fatalf("unexpected, result does not contain subset of expected data") } } func TestIntrospection_SupportsThe__TypeRootField(t *testing.T) { - testType := types.NewObject(types.ObjectConfig{ + testType := NewObject(ObjectConfig{ Name: "TestType", - Fields: types.FieldConfigMap{ - "testField": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "testField": &FieldConfig{ + Type: String, }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: testType, }) if err != nil { @@ -882,36 +877,36 @@ func TestIntrospection_SupportsThe__TypeRootField(t *testing.T) { } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestType", }, }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: schema, RequestString: query, }) if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) { - testType := types.NewObject(types.ObjectConfig{ + testType := NewObject(ObjectConfig{ Name: "TestType", - Fields: types.FieldConfigMap{ - "nonDeprecated": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "nonDeprecated": &FieldConfig{ + Type: String, }, - "deprecated": &types.FieldConfig{ - Type: types.String, + "deprecated": &FieldConfig{ + Type: String, DeprecationReason: "Removed in 1.0", }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: testType, }) if err != nil { @@ -929,7 +924,7 @@ func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) { } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestType", @@ -948,29 +943,29 @@ func TestIntrospection_IdentifiesDeprecatedFields(t *testing.T) { }, }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: schema, RequestString: query, }) - if !testutil.ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + if !ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestIntrospection_RespectsTheIncludeDeprecatedParameterForFields(t *testing.T) { - testType := types.NewObject(types.ObjectConfig{ + testType := NewObject(ObjectConfig{ Name: "TestType", - Fields: types.FieldConfigMap{ - "nonDeprecated": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "nonDeprecated": &FieldConfig{ + Type: String, }, - "deprecated": &types.FieldConfig{ - Type: types.String, + "deprecated": &FieldConfig{ + Type: String, DeprecationReason: "Removed in 1.0", }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: testType, }) if err != nil { @@ -992,7 +987,7 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForFields(t *testing } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestType", @@ -1017,40 +1012,40 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForFields(t *testing }, }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: schema, RequestString: query, }) - if !testutil.ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + if !ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestIntrospection_IdentifiesDeprecatedEnumValues(t *testing.T) { - testEnum := types.NewEnum(types.EnumConfig{ + testEnum := NewEnum(EnumConfig{ Name: "TestEnum", - Values: types.EnumValueConfigMap{ - "NONDEPRECATED": &types.EnumValueConfig{ + Values: EnumValueConfigMap{ + "NONDEPRECATED": &EnumValueConfig{ Value: 0, }, - "DEPRECATED": &types.EnumValueConfig{ + "DEPRECATED": &EnumValueConfig{ Value: 1, DeprecationReason: "Removed in 1.0", }, - "ALSONONDEPRECATED": &types.EnumValueConfig{ + "ALSONONDEPRECATED": &EnumValueConfig{ Value: 2, }, }, }) - testType := types.NewObject(types.ObjectConfig{ + testType := NewObject(ObjectConfig{ Name: "TestType", - Fields: types.FieldConfigMap{ - "testEnum": &types.FieldConfig{ + Fields: FieldConfigMap{ + "testEnum": &FieldConfig{ Type: testEnum, }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: testType, }) if err != nil { @@ -1068,7 +1063,7 @@ func TestIntrospection_IdentifiesDeprecatedEnumValues(t *testing.T) { } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestEnum", @@ -1092,40 +1087,40 @@ func TestIntrospection_IdentifiesDeprecatedEnumValues(t *testing.T) { }, }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: schema, RequestString: query, }) - if !testutil.ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + if !ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestIntrospection_RespectsTheIncludeDeprecatedParameterForEnumValues(t *testing.T) { - testEnum := types.NewEnum(types.EnumConfig{ + testEnum := NewEnum(EnumConfig{ Name: "TestEnum", - Values: types.EnumValueConfigMap{ - "NONDEPRECATED": &types.EnumValueConfig{ + Values: EnumValueConfigMap{ + "NONDEPRECATED": &EnumValueConfig{ Value: 0, }, - "DEPRECATED": &types.EnumValueConfig{ + "DEPRECATED": &EnumValueConfig{ Value: 1, DeprecationReason: "Removed in 1.0", }, - "ALSONONDEPRECATED": &types.EnumValueConfig{ + "ALSONONDEPRECATED": &EnumValueConfig{ Value: 2, }, }, }) - testType := types.NewObject(types.ObjectConfig{ + testType := NewObject(ObjectConfig{ Name: "TestType", - Fields: types.FieldConfigMap{ - "testEnum": &types.FieldConfig{ + Fields: FieldConfigMap{ + "testEnum": &FieldConfig{ Type: testEnum, }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: testType, }) if err != nil { @@ -1147,7 +1142,7 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForEnumValues(t *tes } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__type": map[string]interface{}{ "name": "TestEnum", @@ -1181,25 +1176,25 @@ func TestIntrospection_RespectsTheIncludeDeprecatedParameterForEnumValues(t *tes }, }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: schema, RequestString: query, }) - if !testutil.ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + if !ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestIntrospection_FailsAsExpectedOnThe__TypeRootFieldWithoutAnArg(t *testing.T) { - testType := types.NewObject(types.ObjectConfig{ + testType := NewObject(ObjectConfig{ Name: "TestType", - Fields: types.FieldConfigMap{ - "testField": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "testField": &FieldConfig{ + Type: String, }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: testType, }) if err != nil { @@ -1212,38 +1207,38 @@ func TestIntrospection_FailsAsExpectedOnThe__TypeRootFieldWithoutAnArg(t *testin } } ` - expected := &types.Result{ - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + expected := &Result{ + Errors: []FormattedError{ + FormattedError{ Message: `Field "__type" argument "name" of type "String!" ` + `is required but not provided.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 3, Column: 9}, + Locations: []SourceLocation{ + SourceLocation{Line: 3, Column: 9}, }, }, }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: schema, RequestString: query, }) t.Skipf("Pending `validator` implementation") if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestIntrospection_ExposesDescriptionsOnTypesAndFields(t *testing.T) { - queryRoot := types.NewObject(types.ObjectConfig{ + queryRoot := NewObject(ObjectConfig{ Name: "QueryRoot", - Fields: types.FieldConfigMap{ - "onlyField": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "onlyField": &FieldConfig{ + Type: String, }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: queryRoot, }) if err != nil { @@ -1261,7 +1256,7 @@ func TestIntrospection_ExposesDescriptionsOnTypesAndFields(t *testing.T) { } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "schemaType": map[string]interface{}{ "name": "__Schema", @@ -1291,25 +1286,25 @@ mutation operations.`, }, }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: schema, RequestString: query, }) - if !testutil.ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + if !ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestIntrospection_ExposesDescriptionsOnEnums(t *testing.T) { - queryRoot := types.NewObject(types.ObjectConfig{ + queryRoot := NewObject(ObjectConfig{ Name: "QueryRoot", - Fields: types.FieldConfigMap{ - "onlyField": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "onlyField": &FieldConfig{ + Type: String, }, }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: queryRoot, }) if err != nil { @@ -1327,7 +1322,7 @@ func TestIntrospection_ExposesDescriptionsOnEnums(t *testing.T) { } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "typeKindType": map[string]interface{}{ "name": "__TypeKind", @@ -1369,11 +1364,11 @@ func TestIntrospection_ExposesDescriptionsOnEnums(t *testing.T) { }, }, } - result := g(t, graphql.Params{ + result := g(t, Params{ Schema: schema, RequestString: query, }) - if !testutil.ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + if !ContainSubset(result.Data.(map[string]interface{}), expected.Data.(map[string]interface{})) { + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/kinds/kinds.go b/kinds/kinds.go new file mode 100644 index 00000000..1aafca81 --- /dev/null +++ b/kinds/kinds.go @@ -0,0 +1,38 @@ +package kinds + +const ( + OperationDefinition = "OperationDefinition" + FragmentDefinition = "FragmentDefinition" + Document = "Document" + SelectionSet = "SelectionSet" + Name = "Name" + Directive = "Directive" + VariableDefinition = "VariableDefinition" + Variable = "Variable" + Named = "Named" + List = "List" + NonNull = "NonNull" + InlineFragment = "InlineFragment" + FragmentSpread = "FragmentSpread" + Field = "Field" + Array = "Array" + Argument = "Argument" + IntValue = "IntValue" + FloatValue = "FloatValue" + StringValue = "StringValue" + BooleanValue = "BooleanValue" + EnumValue = "EnumValue" + ListValue = "ListValue" + ObjectValue = "ObjectValue" + ObjectField = "ObjectField" + ObjectDefinition = "ObjectDefinition" + FieldDefinition = "FieldDefinition" + InputValueDefinition = "InputValueDefinition" + InterfaceDefinition = "InterfaceDefinition" + UnionDefinition = "UnionDefinition" + ScalarDefinition = "ScalarDefinition" + EnumDefinition = "EnumDefinition" + EnumValueDefinition = "EnumValueDefinition" + InputObjectDefinition = "InputObjectDefinition" + TypeExtensionDefinition = "TypeExtensionDefinition" +) diff --git a/language/parser/kitchen-sink.graphql b/kitchen-sink.graphql similarity index 100% rename from language/parser/kitchen-sink.graphql rename to kitchen-sink.graphql diff --git a/language/ast/arguments.go b/language/ast/arguments.go deleted file mode 100644 index 93cc7b60..00000000 --- a/language/ast/arguments.go +++ /dev/null @@ -1,33 +0,0 @@ -package ast - -import ( - "github.com/chris-ramon/graphql/language/kinds" -) - -// Argument implements Node -type Argument struct { - Kind string - Loc *Location - Name *Name - Value Value -} - -func NewArgument(arg *Argument) *Argument { - if arg == nil { - arg = &Argument{} - } - return &Argument{ - Kind: kinds.Argument, - Loc: arg.Loc, - Name: arg.Name, - Value: arg.Value, - } -} - -func (arg *Argument) GetKind() string { - return arg.Kind -} - -func (arg *Argument) GetLoc() *Location { - return arg.Loc -} diff --git a/language/ast/definitions.go b/language/ast/definitions.go deleted file mode 100644 index 663945d6..00000000 --- a/language/ast/definitions.go +++ /dev/null @@ -1,153 +0,0 @@ -package ast - -import ( - "github.com/chris-ramon/graphql/language/kinds" -) - -type Definition interface { - // TODO: determine the minimal set of interface for `Definition` - GetOperation() string - GetVariableDefinitions() []*VariableDefinition - GetSelectionSet() *SelectionSet -} - -// Ensure that all definition types implements Definition interface -var _ Definition = (*OperationDefinition)(nil) -var _ Definition = (*FragmentDefinition)(nil) -var _ Definition = (Definition)(nil) - -// OperationDefinition implements Node, Definition -type OperationDefinition struct { - Kind string - Loc *Location - Operation string - Name *Name - VariableDefinitions []*VariableDefinition - Directives []*Directive - SelectionSet *SelectionSet -} - -func NewOperationDefinition(op *OperationDefinition) *OperationDefinition { - if op == nil { - op = &OperationDefinition{} - } - return &OperationDefinition{ - Kind: kinds.OperationDefinition, - Loc: op.Loc, - Operation: op.Operation, - Name: op.Name, - VariableDefinitions: op.VariableDefinitions, - Directives: op.Directives, - SelectionSet: op.SelectionSet, - } -} - -func (op *OperationDefinition) GetKind() string { - return op.Kind -} - -func (op *OperationDefinition) GetLoc() *Location { - return op.Loc -} - -func (op *OperationDefinition) GetOperation() string { - return op.Operation -} - -func (op *OperationDefinition) GetName() *Name { - return op.Name -} - -func (op *OperationDefinition) GetVariableDefinitions() []*VariableDefinition { - return op.VariableDefinitions -} - -func (op *OperationDefinition) GetDirectives() []*Directive { - return op.Directives -} - -func (op *OperationDefinition) GetSelectionSet() *SelectionSet { - return op.SelectionSet -} - -// FragmentDefinition implements Node, Definition -type FragmentDefinition struct { - Kind string - Loc *Location - Operation string - Name *Name - VariableDefinitions []*VariableDefinition - TypeCondition *NamedType - Directives []*Directive - SelectionSet *SelectionSet -} - -func NewFragmentDefinition(fd *FragmentDefinition) *FragmentDefinition { - if fd == nil { - fd = &FragmentDefinition{} - } - return &FragmentDefinition{ - Kind: kinds.FragmentDefinition, - Loc: fd.Loc, - Operation: fd.Operation, - Name: fd.Name, - VariableDefinitions: fd.VariableDefinitions, - TypeCondition: fd.TypeCondition, - Directives: fd.Directives, - SelectionSet: fd.SelectionSet, - } -} - -func (fd *FragmentDefinition) GetKind() string { - return fd.Kind -} - -func (fd *FragmentDefinition) GetLoc() *Location { - return fd.Loc -} - -func (fd *FragmentDefinition) GetOperation() string { - return fd.Operation -} - -func (fd *FragmentDefinition) GetName() *Name { - return fd.Name -} - -func (fd *FragmentDefinition) GetVariableDefinitions() []*VariableDefinition { - return fd.VariableDefinitions -} - -func (fd *FragmentDefinition) GetSelectionSet() *SelectionSet { - return fd.SelectionSet -} - -// VariableDefinition implements Node -type VariableDefinition struct { - Kind string - Loc *Location - Variable *Variable - Type Type - DefaultValue Value -} - -func NewVariableDefinition(vd *VariableDefinition) *VariableDefinition { - if vd == nil { - vd = &VariableDefinition{} - } - return &VariableDefinition{ - Kind: kinds.VariableDefinition, - Loc: vd.Loc, - Variable: vd.Variable, - Type: vd.Type, - DefaultValue: vd.DefaultValue, - } -} - -func (vd *VariableDefinition) GetKind() string { - return vd.Kind -} - -func (vd *VariableDefinition) GetLoc() *Location { - return vd.Loc -} diff --git a/language/ast/directives.go b/language/ast/directives.go deleted file mode 100644 index 7dd49269..00000000 --- a/language/ast/directives.go +++ /dev/null @@ -1,33 +0,0 @@ -package ast - -import ( - "github.com/chris-ramon/graphql/language/kinds" -) - -// Directive implements Node -type Directive struct { - Kind string - Loc *Location - Name *Name - Arguments []*Argument -} - -func NewDirective(dir *Directive) *Directive { - if dir == nil { - dir = &Directive{} - } - return &Directive{ - Kind: kinds.Directive, - Loc: dir.Loc, - Name: dir.Name, - Arguments: dir.Arguments, - } -} - -func (dir *Directive) GetKind() string { - return dir.Kind -} - -func (dir *Directive) GetLoc() *Location { - return dir.Loc -} diff --git a/language/ast/document.go b/language/ast/document.go deleted file mode 100644 index 34385da9..00000000 --- a/language/ast/document.go +++ /dev/null @@ -1,31 +0,0 @@ -package ast - -import ( - "github.com/chris-ramon/graphql/language/kinds" -) - -// Document implements Node -type Document struct { - Kind string - Loc *Location - Definitions []Node -} - -func NewDocument(d *Document) *Document { - if d == nil { - d = &Document{} - } - return &Document{ - Kind: kinds.Document, - Loc: d.Loc, - Definitions: d.Definitions, - } -} - -func (node *Document) GetKind() string { - return node.Kind -} - -func (node *Document) GetLoc() *Location { - return node.Loc -} diff --git a/language/ast/location.go b/language/ast/location.go deleted file mode 100644 index 6f60120c..00000000 --- a/language/ast/location.go +++ /dev/null @@ -1,22 +0,0 @@ -package ast - -import ( - "github.com/chris-ramon/graphql/language/source" -) - -type Location struct { - Start int - End int - Source *source.Source -} - -func NewLocation(loc *Location) *Location { - if loc == nil { - loc = &Location{} - } - return &Location{ - Start: loc.Start, - End: loc.End, - Source: loc.Source, - } -} diff --git a/language/ast/name.go b/language/ast/name.go deleted file mode 100644 index bcce6dd8..00000000 --- a/language/ast/name.go +++ /dev/null @@ -1,29 +0,0 @@ -package ast - -import "github.com/chris-ramon/graphql/language/kinds" - -// Name implements Node -type Name struct { - Kind string - Loc *Location - Value string -} - -func NewName(node *Name) *Name { - if node == nil { - node = &Name{} - } - return &Name{ - Kind: kinds.Name, - Value: node.Value, - Loc: node.Loc, - } -} - -func (node *Name) GetKind() string { - return node.Kind -} - -func (node *Name) GetLoc() *Location { - return node.Loc -} diff --git a/language/ast/node.go b/language/ast/node.go deleted file mode 100644 index f1ba7c70..00000000 --- a/language/ast/node.go +++ /dev/null @@ -1,45 +0,0 @@ -package ast - -type Node interface { - GetKind() string - GetLoc() *Location -} - -// The list of all possible AST node types. -// Ensure that all node types implements Node interface -var _ Node = (*Name)(nil) -var _ Node = (*Document)(nil) -var _ Node = (*OperationDefinition)(nil) -var _ Node = (*VariableDefinition)(nil) -var _ Node = (*Variable)(nil) -var _ Node = (*SelectionSet)(nil) -var _ Node = (*Field)(nil) -var _ Node = (*Argument)(nil) -var _ Node = (*FragmentSpread)(nil) -var _ Node = (*InlineFragment)(nil) -var _ Node = (*FragmentDefinition)(nil) -var _ Node = (*IntValue)(nil) -var _ Node = (*FloatValue)(nil) -var _ Node = (*StringValue)(nil) -var _ Node = (*BooleanValue)(nil) -var _ Node = (*EnumValue)(nil) -var _ Node = (*ListValue)(nil) -var _ Node = (*ObjectValue)(nil) -var _ Node = (*ObjectField)(nil) -var _ Node = (*Directive)(nil) -var _ Node = (*ListType)(nil) -var _ Node = (*NonNullType)(nil) -var _ Node = (*ObjectDefinition)(nil) -var _ Node = (*FieldDefinition)(nil) -var _ Node = (*InputValueDefinition)(nil) -var _ Node = (*InterfaceDefinition)(nil) -var _ Node = (*UnionDefinition)(nil) -var _ Node = (*ScalarDefinition)(nil) -var _ Node = (*EnumDefinition)(nil) -var _ Node = (*EnumValueDefinition)(nil) -var _ Node = (*InputObjectDefinition)(nil) -var _ Node = (*TypeExtensionDefinition)(nil) - -// TODO: File issue in `graphql-js` where NamedType is not -// defined as a Node. This might be a mistake in `graphql-js`? -var _ Node = (*NamedType)(nil) diff --git a/language/ast/selections.go b/language/ast/selections.go deleted file mode 100644 index 953db218..00000000 --- a/language/ast/selections.go +++ /dev/null @@ -1,131 +0,0 @@ -package ast - -import ( - "github.com/chris-ramon/graphql/language/kinds" -) - -type Selection interface { -} - -// Ensure that all definition types implements Selection interface -var _ Selection = (*Field)(nil) -var _ Selection = (*FragmentSpread)(nil) -var _ Selection = (*InlineFragment)(nil) - -// Field implements Node, Selection -type Field struct { - Kind string - Loc *Location - Alias *Name - Name *Name - Arguments []*Argument - Directives []*Directive - SelectionSet *SelectionSet -} - -func NewField(f *Field) *Field { - if f == nil { - f = &Field{} - } - return &Field{ - Kind: kinds.Field, - Loc: f.Loc, - Alias: f.Alias, - Name: f.Name, - Arguments: f.Arguments, - Directives: f.Directives, - SelectionSet: f.SelectionSet, - } -} - -func (f *Field) GetKind() string { - return f.Kind -} - -func (f *Field) GetLoc() *Location { - return f.Loc -} - -// FragmentSpread implements Node, Selection -type FragmentSpread struct { - Kind string - Loc *Location - Name *Name - Directives []*Directive -} - -func NewFragmentSpread(fs *FragmentSpread) *FragmentSpread { - if fs == nil { - fs = &FragmentSpread{} - } - return &FragmentSpread{ - Kind: kinds.FragmentSpread, - Loc: fs.Loc, - Name: fs.Name, - Directives: fs.Directives, - } -} - -func (fs *FragmentSpread) GetKind() string { - return fs.Kind -} - -func (fs *FragmentSpread) GetLoc() *Location { - return fs.Loc -} - -// InlineFragment implements Node, Selection -type InlineFragment struct { - Kind string - Loc *Location - TypeCondition *NamedType - Directives []*Directive - SelectionSet *SelectionSet -} - -func NewInlineFragment(f *InlineFragment) *InlineFragment { - if f == nil { - f = &InlineFragment{} - } - return &InlineFragment{ - Kind: kinds.InlineFragment, - Loc: f.Loc, - TypeCondition: f.TypeCondition, - Directives: f.Directives, - SelectionSet: f.SelectionSet, - } -} - -func (f *InlineFragment) GetKind() string { - return f.Kind -} - -func (f *InlineFragment) GetLoc() *Location { - return f.Loc -} - -// SelectionSet implements Node -type SelectionSet struct { - Kind string - Loc *Location - Selections []Selection -} - -func NewSelectionSet(ss *SelectionSet) *SelectionSet { - if ss == nil { - ss = &SelectionSet{} - } - return &SelectionSet{ - Kind: kinds.SelectionSet, - Loc: ss.Loc, - Selections: ss.Selections, - } -} - -func (ss *SelectionSet) GetKind() string { - return ss.Kind -} - -func (ss *SelectionSet) GetLoc() *Location { - return ss.Loc -} diff --git a/language/ast/type_definitions.go b/language/ast/type_definitions.go deleted file mode 100644 index 2c7ad902..00000000 --- a/language/ast/type_definitions.go +++ /dev/null @@ -1,402 +0,0 @@ -package ast - -import ( - "github.com/chris-ramon/graphql/language/kinds" -) - -// Ensure that all typeDefinition types implements Definition interface -var _ Definition = (*ObjectDefinition)(nil) -var _ Definition = (*InterfaceDefinition)(nil) -var _ Definition = (*UnionDefinition)(nil) -var _ Definition = (*ScalarDefinition)(nil) -var _ Definition = (*EnumDefinition)(nil) -var _ Definition = (*InputObjectDefinition)(nil) -var _ Definition = (*TypeExtensionDefinition)(nil) - -// ObjectDefinition implements Node, Definition -type ObjectDefinition struct { - Kind string - Loc *Location - Name *Name - Interfaces []*NamedType - Fields []*FieldDefinition -} - -func NewObjectDefinition(def *ObjectDefinition) *ObjectDefinition { - if def == nil { - def = &ObjectDefinition{} - } - return &ObjectDefinition{ - Kind: kinds.ObjectDefinition, - Loc: def.Loc, - Name: def.Name, - Interfaces: def.Interfaces, - Fields: def.Fields, - } -} - -func (def *ObjectDefinition) GetKind() string { - return def.Kind -} - -func (def *ObjectDefinition) GetLoc() *Location { - return def.Loc -} - -func (def *ObjectDefinition) GetName() *Name { - return def.Name -} - -func (def *ObjectDefinition) GetVariableDefinitions() []*VariableDefinition { - return []*VariableDefinition{} -} - -func (def *ObjectDefinition) GetSelectionSet() *SelectionSet { - return &SelectionSet{} -} - -func (def *ObjectDefinition) GetOperation() string { - return "" -} - -// FieldDefinition implements Node -type FieldDefinition struct { - Kind string - Loc *Location - Name *Name - Arguments []*InputValueDefinition - Type Type -} - -func NewFieldDefinition(def *FieldDefinition) *FieldDefinition { - if def == nil { - def = &FieldDefinition{} - } - return &FieldDefinition{ - Kind: kinds.FieldDefinition, - Loc: def.Loc, - Name: def.Name, - Arguments: def.Arguments, - Type: def.Type, - } -} - -func (def *FieldDefinition) GetKind() string { - return def.Kind -} - -func (def *FieldDefinition) GetLoc() *Location { - return def.Loc -} - -// InputValueDefinition implements Node -type InputValueDefinition struct { - Kind string - Loc *Location - Name *Name - Type Type - DefaultValue Value -} - -func NewInputValueDefinition(def *InputValueDefinition) *InputValueDefinition { - if def == nil { - def = &InputValueDefinition{} - } - return &InputValueDefinition{ - Kind: kinds.InputValueDefinition, - Loc: def.Loc, - Name: def.Name, - Type: def.Type, - DefaultValue: def.DefaultValue, - } -} - -func (def *InputValueDefinition) GetKind() string { - return def.Kind -} - -func (def *InputValueDefinition) GetLoc() *Location { - return def.Loc -} - -// InterfaceDefinition implements Node, Definition -type InterfaceDefinition struct { - Kind string - Loc *Location - Name *Name - Fields []*FieldDefinition -} - -func NewInterfaceTypeDefinition(def *InterfaceDefinition) *InterfaceDefinition { - if def == nil { - def = &InterfaceDefinition{} - } - return &InterfaceDefinition{ - Kind: kinds.InterfaceDefinition, - Loc: def.Loc, - Name: def.Name, - Fields: def.Fields, - } -} - -func (def *InterfaceDefinition) GetKind() string { - return def.Kind -} - -func (def *InterfaceDefinition) GetLoc() *Location { - return def.Loc -} - -func (def *InterfaceDefinition) GetName() *Name { - return def.Name -} - -func (def *InterfaceDefinition) GetVariableDefinitions() []*VariableDefinition { - return []*VariableDefinition{} -} - -func (def *InterfaceDefinition) GetSelectionSet() *SelectionSet { - return &SelectionSet{} -} - -func (def *InterfaceDefinition) GetOperation() string { - return "" -} - -// UnionDefinition implements Node, Definition -type UnionDefinition struct { - Kind string - Loc *Location - Name *Name - Types []*NamedType -} - -func NewUnionTypeDefinition(def *UnionDefinition) *UnionDefinition { - if def == nil { - def = &UnionDefinition{} - } - return &UnionDefinition{ - Kind: kinds.UnionDefinition, - Loc: def.Loc, - Name: def.Name, - Types: def.Types, - } -} - -func (def *UnionDefinition) GetKind() string { - return def.Kind -} - -func (def *UnionDefinition) GetLoc() *Location { - return def.Loc -} - -func (def *UnionDefinition) GetName() *Name { - return def.Name -} - -func (def *UnionDefinition) GetVariableDefinitions() []*VariableDefinition { - return []*VariableDefinition{} -} - -func (def *UnionDefinition) GetSelectionSet() *SelectionSet { - return &SelectionSet{} -} - -func (def *UnionDefinition) GetOperation() string { - return "" -} - -// ScalarDefinition implements Node, Definition -type ScalarDefinition struct { - Kind string - Loc *Location - Name *Name -} - -func NewScalarTypeDefinition(def *ScalarDefinition) *ScalarDefinition { - if def == nil { - def = &ScalarDefinition{} - } - return &ScalarDefinition{ - Kind: kinds.ScalarDefinition, - Loc: def.Loc, - Name: def.Name, - } -} - -func (def *ScalarDefinition) GetKind() string { - return def.Kind -} - -func (def *ScalarDefinition) GetLoc() *Location { - return def.Loc -} - -func (def *ScalarDefinition) GetName() *Name { - return def.Name -} - -func (def *ScalarDefinition) GetVariableDefinitions() []*VariableDefinition { - return []*VariableDefinition{} -} - -func (def *ScalarDefinition) GetSelectionSet() *SelectionSet { - return &SelectionSet{} -} - -func (def *ScalarDefinition) GetOperation() string { - return "" -} - -// EnumDefinition implements Node, Definition -type EnumDefinition struct { - Kind string - Loc *Location - Name *Name - Values []*EnumValueDefinition -} - -func NewEnumTypeDefinition(def *EnumDefinition) *EnumDefinition { - if def == nil { - def = &EnumDefinition{} - } - return &EnumDefinition{ - Kind: kinds.EnumDefinition, - Loc: def.Loc, - Name: def.Name, - Values: def.Values, - } -} - -func (def *EnumDefinition) GetKind() string { - return def.Kind -} - -func (def *EnumDefinition) GetLoc() *Location { - return def.Loc -} - -func (def *EnumDefinition) GetName() *Name { - return def.Name -} - -func (def *EnumDefinition) GetVariableDefinitions() []*VariableDefinition { - return []*VariableDefinition{} -} - -func (def *EnumDefinition) GetSelectionSet() *SelectionSet { - return &SelectionSet{} -} - -func (def *EnumDefinition) GetOperation() string { - return "" -} - -// EnumValueDefinition implements Node, Definition -type EnumValueDefinition struct { - Kind string - Loc *Location - Name *Name -} - -func NewEnumValueDefinition(def *EnumValueDefinition) *EnumValueDefinition { - if def == nil { - def = &EnumValueDefinition{} - } - return &EnumValueDefinition{ - Kind: kinds.EnumValueDefinition, - Loc: def.Loc, - Name: def.Name, - } -} - -func (def *EnumValueDefinition) GetKind() string { - return def.Kind -} - -func (def *EnumValueDefinition) GetLoc() *Location { - return def.Loc -} - -// InputObjectDefinition implements Node, Definition -type InputObjectDefinition struct { - Kind string - Loc *Location - Name *Name - Fields []*InputValueDefinition -} - -func NewInputObjectTypeDefinition(def *InputObjectDefinition) *InputObjectDefinition { - if def == nil { - def = &InputObjectDefinition{} - } - return &InputObjectDefinition{ - Kind: kinds.InputObjectDefinition, - Loc: def.Loc, - Name: def.Name, - Fields: def.Fields, - } -} - -func (def *InputObjectDefinition) GetKind() string { - return def.Kind -} - -func (def *InputObjectDefinition) GetLoc() *Location { - return def.Loc -} - -func (def *InputObjectDefinition) GetName() *Name { - return def.Name -} - -func (def *InputObjectDefinition) GetVariableDefinitions() []*VariableDefinition { - return []*VariableDefinition{} -} - -func (def *InputObjectDefinition) GetSelectionSet() *SelectionSet { - return &SelectionSet{} -} - -func (def *InputObjectDefinition) GetOperation() string { - return "" -} - -// TypeExtensionDefinition implements Node, Definition -type TypeExtensionDefinition struct { - Kind string - Loc *Location - Definition *ObjectDefinition -} - -func NewTypeExtensionDefinition(def *TypeExtensionDefinition) *TypeExtensionDefinition { - if def == nil { - def = &TypeExtensionDefinition{} - } - return &TypeExtensionDefinition{ - Kind: kinds.TypeExtensionDefinition, - Loc: def.Loc, - Definition: def.Definition, - } -} - -func (def *TypeExtensionDefinition) GetKind() string { - return def.Kind -} - -func (def *TypeExtensionDefinition) GetLoc() *Location { - return def.Loc -} - -func (def *TypeExtensionDefinition) GetVariableDefinitions() []*VariableDefinition { - return []*VariableDefinition{} -} - -func (def *TypeExtensionDefinition) GetSelectionSet() *SelectionSet { - return &SelectionSet{} -} - -func (def *TypeExtensionDefinition) GetOperation() string { - return "" -} diff --git a/language/ast/types.go b/language/ast/types.go deleted file mode 100644 index cdcb25a8..00000000 --- a/language/ast/types.go +++ /dev/null @@ -1,106 +0,0 @@ -package ast - -import ( - "github.com/chris-ramon/graphql/language/kinds" -) - -type Type interface { - GetKind() string - GetLoc() *Location - String() string -} - -// Ensure that all value types implements Value interface -var _ Type = (*NamedType)(nil) -var _ Type = (*ListType)(nil) -var _ Type = (*NonNullType)(nil) - -// NamedType implements Node, Type -type NamedType struct { - Kind string - Loc *Location - Name *Name -} - -func NewNamed(t *NamedType) *NamedType { - if t == nil { - t = &NamedType{} - } - return &NamedType{ - Kind: kinds.NamedType, - Loc: t.Loc, - Name: t.Name, - } -} - -func (t *NamedType) GetKind() string { - return t.Kind -} - -func (t *NamedType) GetLoc() *Location { - return t.Loc -} - -func (t *NamedType) String() string { - return t.GetKind() -} - -// ListType implements Node, Type -type ListType struct { - Kind string - Loc *Location - Type Type -} - -func NewListType(t *ListType) *ListType { - if t == nil { - t = &ListType{} - } - return &ListType{ - Kind: kinds.ListType, - Loc: t.Loc, - Type: t.Type, - } -} - -func (t *ListType) GetKind() string { - return t.Kind -} - -func (t *ListType) GetLoc() *Location { - return t.Loc -} - -func (t *ListType) String() string { - return t.GetKind() -} - -// NonNullType implements Node, Type -type NonNullType struct { - Kind string - Loc *Location - Type Type -} - -func NewNonNullType(t *NonNullType) *NonNullType { - if t == nil { - t = &NonNullType{} - } - return &NonNullType{ - Kind: kinds.NonNullType, - Loc: t.Loc, - Type: t.Type, - } -} - -func (t *NonNullType) GetKind() string { - return t.Kind -} - -func (t *NonNullType) GetLoc() *Location { - return t.Loc -} - -func (t *NonNullType) String() string { - return t.GetKind() -} diff --git a/language/ast/values.go b/language/ast/values.go deleted file mode 100644 index 2b484a66..00000000 --- a/language/ast/values.go +++ /dev/null @@ -1,305 +0,0 @@ -package ast - -import ( - "github.com/chris-ramon/graphql/language/kinds" -) - -type Value interface { - GetValue() interface{} - GetKind() string - GetLoc() *Location -} - -// Ensure that all value types implements Value interface -var _ Value = (*Variable)(nil) -var _ Value = (*IntValue)(nil) -var _ Value = (*FloatValue)(nil) -var _ Value = (*StringValue)(nil) -var _ Value = (*BooleanValue)(nil) -var _ Value = (*EnumValue)(nil) -var _ Value = (*ListValue)(nil) -var _ Value = (*ObjectValue)(nil) - -// Variable implements Node, Value -type Variable struct { - Kind string - Loc *Location - Name *Name -} - -func NewVariable(v *Variable) *Variable { - if v == nil { - v = &Variable{} - } - return &Variable{ - Kind: kinds.Variable, - Loc: v.Loc, - Name: v.Name, - } -} - -func (v *Variable) GetKind() string { - return v.Kind -} - -func (v *Variable) GetLoc() *Location { - return v.Loc -} - -// GetValue alias to Variable.GetName() -func (v *Variable) GetValue() interface{} { - return v.GetName() -} - -func (v *Variable) GetName() interface{} { - return v.Name -} - -// IntValue implements Node, Value -type IntValue struct { - Kind string - Loc *Location - Value string -} - -func NewIntValue(v *IntValue) *IntValue { - if v == nil { - v = &IntValue{} - } - return &IntValue{ - Kind: kinds.IntValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *IntValue) GetKind() string { - return v.Kind -} - -func (v *IntValue) GetLoc() *Location { - return v.Loc -} - -func (v *IntValue) GetValue() interface{} { - return v.Value -} - -// FloatValue implements Node, Value -type FloatValue struct { - Kind string - Loc *Location - Value string -} - -func NewFloatValue(v *FloatValue) *FloatValue { - if v == nil { - v = &FloatValue{} - } - return &FloatValue{ - Kind: kinds.FloatValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *FloatValue) GetKind() string { - return v.Kind -} - -func (v *FloatValue) GetLoc() *Location { - return v.Loc -} - -func (v *FloatValue) GetValue() interface{} { - return v.Value -} - -// StringValue implements Node, Value -type StringValue struct { - Kind string - Loc *Location - Value string -} - -func NewStringValue(v *StringValue) *StringValue { - if v == nil { - v = &StringValue{} - } - return &StringValue{ - Kind: kinds.StringValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *StringValue) GetKind() string { - return v.Kind -} - -func (v *StringValue) GetLoc() *Location { - return v.Loc -} - -func (v *StringValue) GetValue() interface{} { - return v.Value -} - -// BooleanValue implements Node, Value -type BooleanValue struct { - Kind string - Loc *Location - Value bool -} - -func NewBooleanValue(v *BooleanValue) *BooleanValue { - if v == nil { - v = &BooleanValue{} - } - return &BooleanValue{ - Kind: kinds.BooleanValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *BooleanValue) GetKind() string { - return v.Kind -} - -func (v *BooleanValue) GetLoc() *Location { - return v.Loc -} - -func (v *BooleanValue) GetValue() interface{} { - return v.Value -} - -// EnumValue implements Node, Value -type EnumValue struct { - Kind string - Loc *Location - Value string -} - -func NewEnumValue(v *EnumValue) *EnumValue { - if v == nil { - v = &EnumValue{} - } - return &EnumValue{ - Kind: kinds.EnumValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *EnumValue) GetKind() string { - return v.Kind -} - -func (v *EnumValue) GetLoc() *Location { - return v.Loc -} - -func (v *EnumValue) GetValue() interface{} { - return v.Value -} - -// ListValue implements Node, Value -type ListValue struct { - Kind string - Loc *Location - Values []Value -} - -func NewListValue(v *ListValue) *ListValue { - if v == nil { - v = &ListValue{} - } - return &ListValue{ - Kind: kinds.ListValue, - Loc: v.Loc, - Values: v.Values, - } -} - -func (v *ListValue) GetKind() string { - return v.Kind -} - -func (v *ListValue) GetLoc() *Location { - return v.Loc -} - -// GetValue alias to ListValue.GetValues() -func (v *ListValue) GetValue() interface{} { - return v.GetValues() -} - -func (v *ListValue) GetValues() interface{} { - // TODO: verify ObjectValue.GetValue() - return v.Values -} - -// ObjectValue implements Node, Value -type ObjectValue struct { - Kind string - Loc *Location - Fields []*ObjectField -} - -func NewObjectValue(v *ObjectValue) *ObjectValue { - if v == nil { - v = &ObjectValue{} - } - return &ObjectValue{ - Kind: kinds.ObjectValue, - Loc: v.Loc, - Fields: v.Fields, - } -} - -func (v *ObjectValue) GetKind() string { - return v.Kind -} - -func (v *ObjectValue) GetLoc() *Location { - return v.Loc -} - -func (v *ObjectValue) GetValue() interface{} { - // TODO: verify ObjectValue.GetValue() - return v.Fields -} - -// ObjectField implements Node, Value -type ObjectField struct { - Kind string - Name *Name - Loc *Location - Value Value -} - -func NewObjectField(f *ObjectField) *ObjectField { - if f == nil { - f = &ObjectField{} - } - return &ObjectField{ - Kind: kinds.ObjectField, - Loc: f.Loc, - Name: f.Name, - Value: f.Value, - } -} - -func (f *ObjectField) GetKind() string { - return f.Kind -} - -func (f *ObjectField) GetLoc() *Location { - return f.Loc -} - -func (f *ObjectField) GetValue() interface{} { - return f.Value -} diff --git a/language/kinds/kinds.go b/language/kinds/kinds.go deleted file mode 100644 index 9de9e9f2..00000000 --- a/language/kinds/kinds.go +++ /dev/null @@ -1,38 +0,0 @@ -package kinds - -const ( - OperationDefinition = "OperationDefinition" - FragmentDefinition = "FragmentDefinition" - Document = "Document" - SelectionSet = "SelectionSet" - Name = "Name" - Directive = "Directive" - VariableDefinition = "VariableDefinition" - Variable = "Variable" - NamedType = "NamedType" - ListType = "ListType" - NonNullType = "NonNullType" - InlineFragment = "InlineFragment" - FragmentSpread = "FragmentSpread" - Field = "Field" - Array = "Array" - Argument = "Argument" - IntValue = "IntValue" - FloatValue = "FloatValue" - StringValue = "StringValue" - BooleanValue = "BooleanValue" - EnumValue = "EnumValue" - ListValue = "ListValue" - ObjectValue = "ObjectValue" - ObjectField = "ObjectField" - ObjectDefinition = "ObjectDefinition" - FieldDefinition = "FieldDefinition" - InputValueDefinition = "InputValueDefinition" - InterfaceDefinition = "InterfaceDefinition" - UnionDefinition = "UnionDefinition" - ScalarDefinition = "ScalarDefinition" - EnumDefinition = "EnumDefinition" - EnumValueDefinition = "EnumValueDefinition" - InputObjectDefinition = "InputObjectDefinition" - TypeExtensionDefinition = "TypeExtensionDefinition" -) diff --git a/language/parser/schema_parser_test.go b/language/parser/schema_parser_test.go deleted file mode 100644 index d431fed0..00000000 --- a/language/parser/schema_parser_test.go +++ /dev/null @@ -1,759 +0,0 @@ -package parser_test - -import ( - "reflect" - "testing" - - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/language/parser" - "github.com/chris-ramon/graphql/language/source" -) - -func parse(t *testing.T, query string) *ast.Document { - astDoc, err := parser.Parse(parser.ParseParams{ - Source: query, - Options: parser.ParseOptions{ - NoLocation: false, - NoSource: true, - }, - }) - if err != nil { - t.Fatalf("Parse failed: %v", err) - } - return astDoc -} -func loc(start int, end int) *ast.Location { - return &ast.Location{ - Start: start, End: end, - } -} -func TestSchemaParser_SimpleType(t *testing.T) { - - body := ` -type Hello { - world: String -}` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(1, 31), - Definitions: []ast.Node{ - ast.NewObjectDefinition(&ast.ObjectDefinition{ - Loc: loc(1, 31), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(6, 11), - }), - Interfaces: []*ast.NamedType{}, - Fields: []*ast.FieldDefinition{ - ast.NewFieldDefinition(&ast.FieldDefinition{ - Loc: loc(16, 29), - Name: ast.NewName(&ast.Name{ - Value: "world", - Loc: loc(16, 21), - }), - Arguments: []*ast.InputValueDefinition{}, - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(23, 29), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(23, 29), - }), - }), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleExtension(t *testing.T) { - - body := ` -extend type Hello { - world: String -}` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(1, 38), - Definitions: []ast.Node{ - ast.NewTypeExtensionDefinition(&ast.TypeExtensionDefinition{ - Loc: loc(1, 38), - Definition: ast.NewObjectDefinition(&ast.ObjectDefinition{ - Loc: loc(8, 38), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(13, 18), - }), - Interfaces: []*ast.NamedType{}, - Fields: []*ast.FieldDefinition{ - ast.NewFieldDefinition(&ast.FieldDefinition{ - Loc: loc(23, 36), - Name: ast.NewName(&ast.Name{ - Value: "world", - Loc: loc(23, 28), - }), - Arguments: []*ast.InputValueDefinition{}, - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(30, 36), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(30, 36), - }), - }), - }), - }, - }), - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleNonNullType(t *testing.T) { - - body := ` -type Hello { - world: String! -}` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(1, 32), - Definitions: []ast.Node{ - ast.NewObjectDefinition(&ast.ObjectDefinition{ - Loc: loc(1, 32), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(6, 11), - }), - Interfaces: []*ast.NamedType{}, - Fields: []*ast.FieldDefinition{ - ast.NewFieldDefinition(&ast.FieldDefinition{ - Loc: loc(16, 30), - Name: ast.NewName(&ast.Name{ - Value: "world", - Loc: loc(16, 21), - }), - Arguments: []*ast.InputValueDefinition{}, - Type: ast.NewNonNullType(&ast.NonNullType{ - Kind: "NonNullType", - Loc: loc(23, 30), - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(23, 29), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(23, 29), - }), - }), - }), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleTypeInheritingInterface(t *testing.T) { - body := `type Hello implements World { }` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(0, 31), - Definitions: []ast.Node{ - ast.NewObjectDefinition(&ast.ObjectDefinition{ - Loc: loc(0, 31), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(5, 10), - }), - Interfaces: []*ast.NamedType{ - ast.NewNamed(&ast.NamedType{ - Name: ast.NewName(&ast.Name{ - Value: "World", - Loc: loc(22, 27), - }), - Loc: loc(22, 27), - }), - }, - Fields: []*ast.FieldDefinition{}, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleTypeInheritingMultipleInterfaces(t *testing.T) { - body := `type Hello implements Wo, rld { }` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(0, 33), - Definitions: []ast.Node{ - ast.NewObjectDefinition(&ast.ObjectDefinition{ - Loc: loc(0, 33), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(5, 10), - }), - Interfaces: []*ast.NamedType{ - ast.NewNamed(&ast.NamedType{ - Name: ast.NewName(&ast.Name{ - Value: "Wo", - Loc: loc(22, 24), - }), - Loc: loc(22, 24), - }), - ast.NewNamed(&ast.NamedType{ - Name: ast.NewName(&ast.Name{ - Value: "rld", - Loc: loc(26, 29), - }), - Loc: loc(26, 29), - }), - }, - Fields: []*ast.FieldDefinition{}, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SingleValueEnum(t *testing.T) { - body := `enum Hello { WORLD }` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(0, 20), - Definitions: []ast.Node{ - ast.NewEnumTypeDefinition(&ast.EnumDefinition{ - Loc: loc(0, 20), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(5, 10), - }), - Values: []*ast.EnumValueDefinition{ - ast.NewEnumValueDefinition(&ast.EnumValueDefinition{ - Name: ast.NewName(&ast.Name{ - Value: "WORLD", - Loc: loc(13, 18), - }), - Loc: loc(13, 18), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_DoubleValueEnum(t *testing.T) { - body := `enum Hello { WO, RLD }` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(0, 22), - Definitions: []ast.Node{ - ast.NewEnumTypeDefinition(&ast.EnumDefinition{ - Loc: loc(0, 22), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(5, 10), - }), - Values: []*ast.EnumValueDefinition{ - ast.NewEnumValueDefinition(&ast.EnumValueDefinition{ - Name: ast.NewName(&ast.Name{ - Value: "WO", - Loc: loc(13, 15), - }), - Loc: loc(13, 15), - }), - ast.NewEnumValueDefinition(&ast.EnumValueDefinition{ - Name: ast.NewName(&ast.Name{ - Value: "RLD", - Loc: loc(17, 20), - }), - Loc: loc(17, 20), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleInterface(t *testing.T) { - body := ` -interface Hello { - world: String -}` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(1, 36), - Definitions: []ast.Node{ - ast.NewInterfaceTypeDefinition(&ast.InterfaceDefinition{ - Loc: loc(1, 36), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(11, 16), - }), - Fields: []*ast.FieldDefinition{ - ast.NewFieldDefinition(&ast.FieldDefinition{ - Loc: loc(21, 34), - Name: ast.NewName(&ast.Name{ - Value: "world", - Loc: loc(21, 26), - }), - Arguments: []*ast.InputValueDefinition{}, - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(28, 34), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(28, 34), - }), - }), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleFieldWithArg(t *testing.T) { - body := ` -type Hello { - world(flag: Boolean): String -}` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(1, 46), - Definitions: []ast.Node{ - ast.NewObjectDefinition(&ast.ObjectDefinition{ - Loc: loc(1, 46), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(6, 11), - }), - Interfaces: []*ast.NamedType{}, - Fields: []*ast.FieldDefinition{ - ast.NewFieldDefinition(&ast.FieldDefinition{ - Loc: loc(16, 44), - Name: ast.NewName(&ast.Name{ - Value: "world", - Loc: loc(16, 21), - }), - Arguments: []*ast.InputValueDefinition{ - ast.NewInputValueDefinition(&ast.InputValueDefinition{ - Loc: loc(22, 35), - Name: ast.NewName(&ast.Name{ - Value: "flag", - Loc: loc(22, 26), - }), - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(28, 35), - Name: ast.NewName(&ast.Name{ - Value: "Boolean", - Loc: loc(28, 35), - }), - }), - DefaultValue: nil, - }), - }, - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(38, 44), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(38, 44), - }), - }), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleFieldWithArgWithDefaultValue(t *testing.T) { - body := ` -type Hello { - world(flag: Boolean = true): String -}` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(1, 53), - Definitions: []ast.Node{ - ast.NewObjectDefinition(&ast.ObjectDefinition{ - Loc: loc(1, 53), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(6, 11), - }), - Interfaces: []*ast.NamedType{}, - Fields: []*ast.FieldDefinition{ - ast.NewFieldDefinition(&ast.FieldDefinition{ - Loc: loc(16, 51), - Name: ast.NewName(&ast.Name{ - Value: "world", - Loc: loc(16, 21), - }), - Arguments: []*ast.InputValueDefinition{ - ast.NewInputValueDefinition(&ast.InputValueDefinition{ - Loc: loc(22, 42), - Name: ast.NewName(&ast.Name{ - Value: "flag", - Loc: loc(22, 26), - }), - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(28, 35), - Name: ast.NewName(&ast.Name{ - Value: "Boolean", - Loc: loc(28, 35), - }), - }), - DefaultValue: ast.NewBooleanValue(&ast.BooleanValue{ - Value: true, - Loc: loc(38, 42), - }), - }), - }, - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(45, 51), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(45, 51), - }), - }), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleFieldWithListArg(t *testing.T) { - body := ` -type Hello { - world(things: [String]): String -}` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(1, 49), - Definitions: []ast.Node{ - ast.NewObjectDefinition(&ast.ObjectDefinition{ - Loc: loc(1, 49), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(6, 11), - }), - Interfaces: []*ast.NamedType{}, - Fields: []*ast.FieldDefinition{ - ast.NewFieldDefinition(&ast.FieldDefinition{ - Loc: loc(16, 47), - Name: ast.NewName(&ast.Name{ - Value: "world", - Loc: loc(16, 21), - }), - Arguments: []*ast.InputValueDefinition{ - ast.NewInputValueDefinition(&ast.InputValueDefinition{ - Loc: loc(22, 38), - Name: ast.NewName(&ast.Name{ - Value: "things", - Loc: loc(22, 28), - }), - Type: ast.NewListType(&ast.ListType{ - Loc: loc(30, 38), - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(31, 37), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(31, 37), - }), - }), - }), - DefaultValue: nil, - }), - }, - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(41, 47), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(41, 47), - }), - }), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleFieldWithTwoArg(t *testing.T) { - body := ` -type Hello { - world(argOne: Boolean, argTwo: Int): String -}` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(1, 61), - Definitions: []ast.Node{ - ast.NewObjectDefinition(&ast.ObjectDefinition{ - Loc: loc(1, 61), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(6, 11), - }), - Interfaces: []*ast.NamedType{}, - Fields: []*ast.FieldDefinition{ - ast.NewFieldDefinition(&ast.FieldDefinition{ - Loc: loc(16, 59), - Name: ast.NewName(&ast.Name{ - Value: "world", - Loc: loc(16, 21), - }), - Arguments: []*ast.InputValueDefinition{ - ast.NewInputValueDefinition(&ast.InputValueDefinition{ - Loc: loc(22, 37), - Name: ast.NewName(&ast.Name{ - Value: "argOne", - Loc: loc(22, 28), - }), - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(30, 37), - Name: ast.NewName(&ast.Name{ - Value: "Boolean", - Loc: loc(30, 37), - }), - }), - DefaultValue: nil, - }), - ast.NewInputValueDefinition(&ast.InputValueDefinition{ - Loc: loc(39, 50), - Name: ast.NewName(&ast.Name{ - Value: "argTwo", - Loc: loc(39, 45), - }), - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(47, 50), - Name: ast.NewName(&ast.Name{ - Value: "Int", - Loc: loc(47, 50), - }), - }), - DefaultValue: nil, - }), - }, - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(53, 59), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(53, 59), - }), - }), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleUnion(t *testing.T) { - body := `union Hello = World` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(0, 19), - Definitions: []ast.Node{ - ast.NewUnionTypeDefinition(&ast.UnionDefinition{ - Loc: loc(0, 19), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(6, 11), - }), - Types: []*ast.NamedType{ - ast.NewNamed(&ast.NamedType{ - Loc: loc(14, 19), - Name: ast.NewName(&ast.Name{ - Value: "World", - Loc: loc(14, 19), - }), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_UnionWithTwoTypes(t *testing.T) { - body := `union Hello = Wo | Rld` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(0, 22), - Definitions: []ast.Node{ - ast.NewUnionTypeDefinition(&ast.UnionDefinition{ - Loc: loc(0, 22), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(6, 11), - }), - Types: []*ast.NamedType{ - ast.NewNamed(&ast.NamedType{ - Loc: loc(14, 16), - Name: ast.NewName(&ast.Name{ - Value: "Wo", - Loc: loc(14, 16), - }), - }), - ast.NewNamed(&ast.NamedType{ - Loc: loc(19, 22), - Name: ast.NewName(&ast.Name{ - Value: "Rld", - Loc: loc(19, 22), - }), - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_Scalar(t *testing.T) { - body := `scalar Hello` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(0, 12), - Definitions: []ast.Node{ - ast.NewScalarTypeDefinition(&ast.ScalarDefinition{ - Loc: loc(0, 12), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(7, 12), - }), - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleInputObject(t *testing.T) { - body := ` -input Hello { - world: String -}` - astDoc := parse(t, body) - expected := ast.NewDocument(&ast.Document{ - Loc: loc(1, 32), - Definitions: []ast.Node{ - ast.NewInputObjectTypeDefinition(&ast.InputObjectDefinition{ - Loc: loc(1, 32), - Name: ast.NewName(&ast.Name{ - Value: "Hello", - Loc: loc(7, 12), - }), - Fields: []*ast.InputValueDefinition{ - ast.NewInputValueDefinition(&ast.InputValueDefinition{ - Loc: loc(17, 30), - Name: ast.NewName(&ast.Name{ - Value: "world", - Loc: loc(17, 22), - }), - Type: ast.NewNamed(&ast.NamedType{ - Loc: loc(24, 30), - Name: ast.NewName(&ast.Name{ - Value: "String", - Loc: loc(24, 30), - }), - }), - DefaultValue: nil, - }), - }, - }), - }, - }) - if !reflect.DeepEqual(astDoc, expected) { - t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) - } -} - -func TestSchemaParser_SimpleInputObjectWithArgsShouldFail(t *testing.T) { - body := ` -input Hello { - world(foo: Int): String -}` - - _, err := parser.Parse(parser.ParseParams{ - Source: body, - Options: parser.ParseOptions{ - NoLocation: false, - NoSource: true, - }, - }) - - expectedError := &graphqlerrors.Error{ - Message: `Syntax Error GraphQL (3:8) Expected :, found ( - -2: input Hello { -3: world(foo: Int): String - ^ -4: } -`, - Stack: `Syntax Error GraphQL (3:8) Expected :, found ( - -2: input Hello { -3: world(foo: Int): String - ^ -4: } -`, - Nodes: []ast.Node{}, - Source: &source.Source{ - Body: ` -input Hello { - world(foo: Int): String -}`, - Name: "GraphQL", - }, - Positions: []int{22}, - Locations: []location.SourceLocation{ - {Line: 3, Column: 8}, - }, - } - if err == nil { - t.Fatalf("expected error, expected: %v, got: %v", expectedError, nil) - } - if !reflect.DeepEqual(expectedError, err) { - t.Fatalf("unexpected document, expected: %v, got: %v", expectedError, err) - } -} diff --git a/language/lexer/lexer.go b/lexer.go similarity index 91% rename from language/lexer/lexer.go rename to lexer.go index 28ad4c8f..10004ecc 100644 --- a/language/lexer/lexer.go +++ b/lexer.go @@ -1,10 +1,7 @@ -package lexer +package graphql import ( "fmt" - - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/source" ) const ( @@ -88,7 +85,7 @@ func (t *Token) String() string { type Lexer func(resetPosition int) (Token, error) -func Lex(s *source.Source) Lexer { +func Lex(s *Source) Lexer { var prevPosition int return func(resetPosition int) (Token, error) { if resetPosition == 0 { @@ -105,7 +102,7 @@ func Lex(s *source.Source) Lexer { // Reads an alphanumeric + underscore name from the source. // [_A-Za-z][_0-9A-Za-z]* -func readName(source *source.Source, position int) Token { +func readName(source *Source, position int) Token { body := source.Body bodyLength := len(body) end := position + 1 @@ -128,7 +125,7 @@ func readName(source *source.Source, position int) Token { // or an int depending on whether a decimal point appears. // Int: -?(0|[1-9][0-9]*) // Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? -func readNumber(s *source.Source, start int, firstCode rune) (Token, error) { +func readNumber(s *Source, start int, firstCode rune) (Token, error) { code := firstCode body := s.Body position := start @@ -142,7 +139,7 @@ func readNumber(s *source.Source, start int, firstCode rune) (Token, error) { code = charCodeAt(body, position) if code >= 48 && code <= 57 { description := fmt.Sprintf("Invalid number, unexpected digit after 0: \"%c\".", code) - return Token{}, graphqlerrors.NewSyntaxError(s, position, description) + return Token{}, NewSyntaxError(s, position, description) } } else { p, err := readDigits(s, position, code) @@ -185,7 +182,7 @@ func readNumber(s *source.Source, start int, firstCode rune) (Token, error) { } // Returns the new position in the source after reading digits. -func readDigits(s *source.Source, start int, firstCode rune) (int, error) { +func readDigits(s *Source, start int, firstCode rune) (int, error) { body := s.Body position := start code := firstCode @@ -207,10 +204,10 @@ func readDigits(s *source.Source, start int, firstCode rune) (int, error) { } else { description = fmt.Sprintf("Invalid number, expected digit but got: EOF.") } - return position, graphqlerrors.NewSyntaxError(s, position, description) + return position, NewSyntaxError(s, position, description) } -func readString(s *source.Source, start int) (Token, error) { +func readString(s *Source, start int) (Token, error) { body := s.Body position := start + 1 chunkStart := position @@ -256,13 +253,13 @@ func readString(s *source.Source, start int) (Token, error) { charCodeAt(body, position+4), ) if charCode < 0 { - return Token{}, graphqlerrors.NewSyntaxError(s, position, "Bad character escape sequence.") + return Token{}, NewSyntaxError(s, position, "Bad character escape sequence.") } value += fmt.Sprintf("%c", charCode) position += 4 break default: - return Token{}, graphqlerrors.NewSyntaxError(s, position, "Bad character escape sequence.") + return Token{}, NewSyntaxError(s, position, "Bad character escape sequence.") } position += 1 chunkStart = position @@ -273,7 +270,7 @@ func readString(s *source.Source, start int) (Token, error) { } } if code != 34 { - return Token{}, graphqlerrors.NewSyntaxError(s, position, "Unterminated string.") + return Token{}, NewSyntaxError(s, position, "Unterminated string.") } value += body[chunkStart:position] return makeToken(TokenKind[STRING], start, position+1, value), nil @@ -310,7 +307,7 @@ func makeToken(kind int, start int, end int, value string) Token { return Token{Kind: kind, Start: start, End: end, Value: value} } -func readToken(s *source.Source, fromPosition int) (Token, error) { +func readToken(s *Source, fromPosition int) (Token, error) { body := s.Body bodyLength := len(body) position := positionAfterWhitespace(body, fromPosition) @@ -388,7 +385,7 @@ func readToken(s *source.Source, fromPosition int) (Token, error) { return token, nil } description := fmt.Sprintf("Unexpected character \"%c\".", code) - return Token{}, graphqlerrors.NewSyntaxError(s, position, description) + return Token{}, NewSyntaxError(s, position, description) } func charCodeAt(body string, position int) rune { diff --git a/language/lexer/lexer_test.go b/lexer_test.go similarity index 97% rename from language/lexer/lexer_test.go rename to lexer_test.go index ac56ee73..894f268e 100644 --- a/language/lexer/lexer_test.go +++ b/lexer_test.go @@ -1,10 +1,8 @@ -package lexer +package graphql import ( "reflect" "testing" - - "github.com/chris-ramon/graphql/language/source" ) type Test struct { @@ -12,8 +10,8 @@ type Test struct { Expected interface{} } -func createSource(body string) *source.Source { - return source.NewSource(&source.Source{Body: body}) +func createSource(body string) *Source { + return NewSource(&Source{Body: body}) } func TestSkipsWhiteSpace(t *testing.T) { @@ -54,7 +52,7 @@ func TestSkipsWhiteSpace(t *testing.T) { }, } for _, test := range tests { - token, err := Lex(&source.Source{Body: test.Body})(0) + token, err := Lex(&Source{Body: test.Body})(0) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -138,7 +136,7 @@ func TestLexesStrings(t *testing.T) { }, } for _, test := range tests { - token, err := Lex(&source.Source{Body: test.Body})(0) + token, err := Lex(&Source{Body: test.Body})(0) if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/executor/lists_test.go b/lists_test.go similarity index 74% rename from executor/lists_test.go rename to lists_test.go index 1c0caf65..57dfd0d4 100644 --- a/executor/lists_test.go +++ b/lists_test.go @@ -1,36 +1,31 @@ -package executor_test +package graphql import ( - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) -func checkList(t *testing.T, testType types.Type, testData interface{}, expected *types.Result) { +func checkList(t *testing.T, testType Type, testData interface{}, expected *Result) { data := map[string]interface{}{ "test": testData, } - dataType := types.NewObject(types.ObjectConfig{ + dataType := NewObject(ObjectConfig{ Name: "DataType", - Fields: types.FieldConfigMap{ - "test": &types.FieldConfig{ + Fields: FieldConfigMap{ + "test": &FieldConfig{ Type: testType, }, }, }) - dataType.AddFieldConfig("nest", &types.FieldConfig{ + dataType.AddFieldConfig("nest", &FieldConfig{ Type: dataType, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { return data }, }) - schema, err := types.NewSchema(types.SchemaConfig{ + schema, err := NewSchema(SchemaConfig{ Query: dataType, }) if err != nil { @@ -38,31 +33,31 @@ func checkList(t *testing.T, testType types.Type, testData interface{}, expected } // parse query - ast := testutil.Parse(t, `{ nest { test } }`) + ast := TestParse(t, `{ nest { test } }`) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema, AST: ast, Root: data, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(expected.Errors) != len(result.Errors) { - t.Fatalf("wrong result, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("wrong result, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } // Describe [T] Array func TestLists_ListOfNullableObjects_ContainsValues(t *testing.T) { - ttype := types.NewList(types.Int) + ttype := NewList(Int) data := []interface{}{ 1, 2, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -74,11 +69,11 @@ func TestLists_ListOfNullableObjects_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableObjects_ContainsNull(t *testing.T) { - ttype := types.NewList(types.Int) + ttype := NewList(Int) data := []interface{}{ 1, nil, 2, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -90,8 +85,8 @@ func TestLists_ListOfNullableObjects_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableObjects_ReturnsNull(t *testing.T) { - ttype := types.NewList(types.Int) - expected := &types.Result{ + ttype := NewList(Int) + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, @@ -103,7 +98,7 @@ func TestLists_ListOfNullableObjects_ReturnsNull(t *testing.T) { // Describe [T] Func()Array // equivalent to Promise> func TestLists_ListOfNullableFunc_ContainsValues(t *testing.T) { - ttype := types.NewList(types.Int) + ttype := NewList(Int) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -112,7 +107,7 @@ func TestLists_ListOfNullableFunc_ContainsValues(t *testing.T) { 1, 2, } } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -124,7 +119,7 @@ func TestLists_ListOfNullableFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableFunc_ContainsNull(t *testing.T) { - ttype := types.NewList(types.Int) + ttype := NewList(Int) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -133,7 +128,7 @@ func TestLists_ListOfNullableFunc_ContainsNull(t *testing.T) { 1, nil, 2, } } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -145,14 +140,14 @@ func TestLists_ListOfNullableFunc_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableFunc_ReturnsNull(t *testing.T) { - ttype := types.NewList(types.Int) + ttype := NewList(Int) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` data := func() interface{} { return nil } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, @@ -164,7 +159,7 @@ func TestLists_ListOfNullableFunc_ReturnsNull(t *testing.T) { // Describe [T] Array> // equivalent to Array> func TestLists_ListOfNullableArrayOfFuncContainsValues(t *testing.T) { - ttype := types.NewList(types.Int) + ttype := NewList(Int) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -176,7 +171,7 @@ func TestLists_ListOfNullableArrayOfFuncContainsValues(t *testing.T) { return 2 }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -188,7 +183,7 @@ func TestLists_ListOfNullableArrayOfFuncContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_ListOfNullableArrayOfFuncContainsNulls(t *testing.T) { - ttype := types.NewList(types.Int) + ttype := NewList(Int) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -203,7 +198,7 @@ func TestLists_ListOfNullableArrayOfFuncContainsNulls(t *testing.T) { return 2 }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -217,11 +212,11 @@ func TestLists_ListOfNullableArrayOfFuncContainsNulls(t *testing.T) { // Describe [T]! Array func TestLists_NonNullListOfNullableObjectsContainsValues(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.Int)) + ttype := NewNonNull(NewList(Int)) data := []interface{}{ 1, 2, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -233,11 +228,11 @@ func TestLists_NonNullListOfNullableObjectsContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableObjectsContainsNull(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.Int)) + ttype := NewNonNull(NewList(Int)) data := []interface{}{ 1, nil, 2, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -249,16 +244,16 @@ func TestLists_NonNullListOfNullableObjectsContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableObjectsReturnsNull(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.Int)) - expected := &types.Result{ + ttype := NewNonNull(NewList(Int)) + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 1, Column: 10, }, @@ -271,7 +266,7 @@ func TestLists_NonNullListOfNullableObjectsReturnsNull(t *testing.T) { // Describe [T]! Func()Array // equivalent to Promise> func TestLists_NonNullListOfNullableFunc_ContainsValues(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.Int)) + ttype := NewNonNull(NewList(Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -280,7 +275,7 @@ func TestLists_NonNullListOfNullableFunc_ContainsValues(t *testing.T) { 1, 2, } } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -292,7 +287,7 @@ func TestLists_NonNullListOfNullableFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableFunc_ContainsNull(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.Int)) + ttype := NewNonNull(NewList(Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -301,7 +296,7 @@ func TestLists_NonNullListOfNullableFunc_ContainsNull(t *testing.T) { 1, nil, 2, } } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -313,22 +308,22 @@ func TestLists_NonNullListOfNullableFunc_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableFunc_ReturnsNull(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.Int)) + ttype := NewNonNull(NewList(Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` data := func() interface{} { return nil } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 1, Column: 10, }, @@ -341,7 +336,7 @@ func TestLists_NonNullListOfNullableFunc_ReturnsNull(t *testing.T) { // Describe [T]! Array> // equivalent to Array> func TestLists_NonNullListOfNullableArrayOfFunc_ContainsValues(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.Int)) + ttype := NewNonNull(NewList(Int)) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -353,7 +348,7 @@ func TestLists_NonNullListOfNullableArrayOfFunc_ContainsValues(t *testing.T) { return 2 }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -365,7 +360,7 @@ func TestLists_NonNullListOfNullableArrayOfFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNullableArrayOfFunc_ContainsNulls(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.Int)) + ttype := NewNonNull(NewList(Int)) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -380,7 +375,7 @@ func TestLists_NonNullListOfNullableArrayOfFunc_ContainsNulls(t *testing.T) { return 2 }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -394,11 +389,11 @@ func TestLists_NonNullListOfNullableArrayOfFunc_ContainsNulls(t *testing.T) { // Describe [T!] Array func TestLists_NullableListOfNonNullObjects_ContainsValues(t *testing.T) { - ttype := types.NewList(types.NewNonNull(types.Int)) + ttype := NewList(NewNonNull(Int)) data := []interface{}{ 1, 2, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -410,21 +405,21 @@ func TestLists_NullableListOfNonNullObjects_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullObjects_ContainsNull(t *testing.T) { - ttype := types.NewList(types.NewNonNull(types.Int)) + ttype := NewList(NewNonNull(Int)) data := []interface{}{ 1, nil, 2, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, }, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 1, Column: 10, }, @@ -435,9 +430,9 @@ func TestLists_NullableListOfNonNullObjects_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullObjects_ReturnsNull(t *testing.T) { - ttype := types.NewList(types.NewNonNull(types.Int)) + ttype := NewList(NewNonNull(Int)) - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, @@ -449,7 +444,7 @@ func TestLists_NullableListOfNonNullObjects_ReturnsNull(t *testing.T) { // Describe [T!] Func()Array // equivalent to Promise> func TestLists_NullableListOfNonNullFunc_ContainsValues(t *testing.T) { - ttype := types.NewList(types.NewNonNull(types.Int)) + ttype := NewList(NewNonNull(Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -458,7 +453,7 @@ func TestLists_NullableListOfNonNullFunc_ContainsValues(t *testing.T) { 1, 2, } } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -470,7 +465,7 @@ func TestLists_NullableListOfNonNullFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullFunc_ContainsNull(t *testing.T) { - ttype := types.NewList(types.NewNonNull(types.Int)) + ttype := NewList(NewNonNull(Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -479,17 +474,17 @@ func TestLists_NullableListOfNonNullFunc_ContainsNull(t *testing.T) { 1, nil, 2, } } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, }, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 1, Column: 10, }, @@ -500,14 +495,14 @@ func TestLists_NullableListOfNonNullFunc_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullFunc_ReturnsNull(t *testing.T) { - ttype := types.NewList(types.NewNonNull(types.Int)) + ttype := NewList(NewNonNull(Int)) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` data := func() interface{} { return nil } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": nil, @@ -519,7 +514,7 @@ func TestLists_NullableListOfNonNullFunc_ReturnsNull(t *testing.T) { // Describe [T!] Array> // equivalent to Array> func TestLists_NullableListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { - ttype := types.NewList(types.NewNonNull(types.Int)) + ttype := NewList(NewNonNull(Int)) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -531,7 +526,7 @@ func TestLists_NullableListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { return 2 }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -543,7 +538,7 @@ func TestLists_NullableListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NullableListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { - ttype := types.NewList(types.NewNonNull(types.Int)) + ttype := NewList(NewNonNull(Int)) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -558,7 +553,7 @@ func TestLists_NullableListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { return 2 }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -572,11 +567,11 @@ func TestLists_NullableListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { // Describe [T!]! Array func TestLists_NonNullListOfNonNullObjects_ContainsValues(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) + ttype := NewNonNull(NewList(NewNonNull(Int))) data := []interface{}{ 1, 2, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -588,19 +583,19 @@ func TestLists_NonNullListOfNonNullObjects_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullObjects_ContainsNull(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) + ttype := NewNonNull(NewList(NewNonNull(Int))) data := []interface{}{ 1, nil, 2, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 1, Column: 10, }, @@ -611,17 +606,17 @@ func TestLists_NonNullListOfNonNullObjects_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullObjects_ReturnsNull(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) + ttype := NewNonNull(NewList(NewNonNull(Int))) - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 1, Column: 10, }, @@ -634,7 +629,7 @@ func TestLists_NonNullListOfNonNullObjects_ReturnsNull(t *testing.T) { // Describe [T!]! Func()Array // equivalent to Promise> func TestLists_NonNullListOfNonNullFunc_ContainsValues(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) + ttype := NewNonNull(NewList(NewNonNull(Int))) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -643,7 +638,7 @@ func TestLists_NonNullListOfNonNullFunc_ContainsValues(t *testing.T) { 1, 2, } } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -655,7 +650,7 @@ func TestLists_NonNullListOfNonNullFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullFunc_ContainsNull(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) + ttype := NewNonNull(NewList(NewNonNull(Int))) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -664,15 +659,15 @@ func TestLists_NonNullListOfNonNullFunc_ContainsNull(t *testing.T) { 1, nil, 2, } } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 1, Column: 10, }, @@ -683,22 +678,22 @@ func TestLists_NonNullListOfNonNullFunc_ContainsNull(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullFunc_ReturnsNull(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) + ttype := NewNonNull(NewList(NewNonNull(Int))) // `data` is a function that return values // Note that its uses the expected signature `func() interface{} {...}` data := func() interface{} { return nil } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 1, Column: 10, }, @@ -711,7 +706,7 @@ func TestLists_NonNullListOfNonNullFunc_ReturnsNull(t *testing.T) { // Describe [T!]! Array> // equivalent to Array> func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) + ttype := NewNonNull(NewList(NewNonNull(Int))) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -723,7 +718,7 @@ func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { return 2 }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ @@ -735,7 +730,7 @@ func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsValues(t *testing.T) { checkList(t, ttype, data, expected) } func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { - ttype := types.NewNonNull(types.NewList(types.NewNonNull(types.Int))) + ttype := NewNonNull(NewList(NewNonNull(Int))) // `data` is a slice of functions that return values // Note that its uses the expected signature `func() interface{} {...}` @@ -750,7 +745,7 @@ func TestLists_NonNullListOfNonNullArrayOfFunc_ContainsNulls(t *testing.T) { return 2 }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "test": []interface{}{ diff --git a/errors/located.go b/located.go similarity index 59% rename from errors/located.go rename to located.go index 273a29c9..f655c212 100644 --- a/errors/located.go +++ b/located.go @@ -1,10 +1,6 @@ -package graphqlerrors +package graphql -import ( - "github.com/chris-ramon/graphql/language/ast" -) - -func NewLocatedError(err interface{}, nodes []ast.Node) *Error { +func NewLocatedError(err interface{}, nodes []Node) *Error { message := "An unknown error occurred." if err, ok := err.(error); ok { message = err.Error() @@ -22,8 +18,8 @@ func NewLocatedError(err interface{}, nodes []ast.Node) *Error { ) } -func FieldASTsToNodeASTs(fieldASTs []*ast.Field) []ast.Node { - nodes := []ast.Node{} +func FieldASTsToNodeASTs(fieldASTs []*AstField) []Node { + nodes := []Node{} for _, fieldAST := range fieldASTs { nodes = append(nodes, fieldAST) } diff --git a/language/location/location.go b/location.go similarity index 80% rename from language/location/location.go rename to location.go index 6ec9784d..022d2d84 100644 --- a/language/location/location.go +++ b/location.go @@ -1,9 +1,7 @@ -package location +package graphql import ( "regexp" - - "github.com/chris-ramon/graphql/language/source" ) type SourceLocation struct { @@ -11,7 +9,7 @@ type SourceLocation struct { Column int } -func GetLocation(s *source.Source, position int) SourceLocation { +func GetLocation(s *Source, position int) SourceLocation { body := "" if s != nil { body = s.Body diff --git a/executor/mutations_test.go b/mutations_test.go similarity index 65% rename from executor/mutations_test.go rename to mutations_test.go index 2b3032dd..58ba158b 100644 --- a/executor/mutations_test.go +++ b/mutations_test.go @@ -1,11 +1,6 @@ -package executor_test +package graphql import ( - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) @@ -38,77 +33,77 @@ func (r *testRoot) PromiseAndFailToChangeTheNumber(newNumber int) *testNumberHol } // numberHolderType creates a mapping to testNumberHolder -var numberHolderType = types.NewObject(types.ObjectConfig{ +var numberHolderType = NewObject(ObjectConfig{ Name: "NumberHolder", - Fields: types.FieldConfigMap{ - "theNumber": &types.FieldConfig{ - Type: types.Int, + Fields: FieldConfigMap{ + "theNumber": &FieldConfig{ + Type: Int, }, }, }) -var mutationsTestSchema, _ = types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ +var mutationsTestSchema, _ = NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "numberHolder": &types.FieldConfig{ + Fields: FieldConfigMap{ + "numberHolder": &FieldConfig{ Type: numberHolderType, }, }, }), - Mutation: types.NewObject(types.ObjectConfig{ + Mutation: NewObject(ObjectConfig{ Name: "Mutation", - Fields: types.FieldConfigMap{ - "immediatelyChangeTheNumber": &types.FieldConfig{ + Fields: FieldConfigMap{ + "immediatelyChangeTheNumber": &FieldConfig{ Type: numberHolderType, - Args: types.FieldConfigArgument{ - "newNumber": &types.ArgumentConfig{ - Type: types.Int, + Args: FieldConfigArgument{ + "newNumber": &ArgumentConfig{ + Type: Int, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { newNumber := 0 obj, _ := p.Source.(*testRoot) newNumber, _ = p.Args["newNumber"].(int) return obj.ImmediatelyChangeTheNumber(newNumber) }, }, - "promiseToChangeTheNumber": &types.FieldConfig{ + "promiseToChangeTheNumber": &FieldConfig{ Type: numberHolderType, - Args: types.FieldConfigArgument{ - "newNumber": &types.ArgumentConfig{ - Type: types.Int, + Args: FieldConfigArgument{ + "newNumber": &ArgumentConfig{ + Type: Int, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { newNumber := 0 obj, _ := p.Source.(*testRoot) newNumber, _ = p.Args["newNumber"].(int) return obj.PromiseToChangeTheNumber(newNumber) }, }, - "failToChangeTheNumber": &types.FieldConfig{ + "failToChangeTheNumber": &FieldConfig{ Type: numberHolderType, - Args: types.FieldConfigArgument{ - "newNumber": &types.ArgumentConfig{ - Type: types.Int, + Args: FieldConfigArgument{ + "newNumber": &ArgumentConfig{ + Type: Int, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { newNumber := 0 obj, _ := p.Source.(*testRoot) newNumber, _ = p.Args["newNumber"].(int) return obj.FailToChangeTheNumber(newNumber) }, }, - "promiseAndFailToChangeTheNumber": &types.FieldConfig{ + "promiseAndFailToChangeTheNumber": &FieldConfig{ Type: numberHolderType, - Args: types.FieldConfigArgument{ - "newNumber": &types.ArgumentConfig{ - Type: types.Int, + Args: FieldConfigArgument{ + "newNumber": &ArgumentConfig{ + Type: Int, }, }, - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { newNumber := 0 obj, _ := p.Source.(*testRoot) newNumber, _ = p.Args["newNumber"].(int) @@ -140,7 +135,7 @@ func TestMutations_ExecutionOrdering_EvaluatesMutationsSerially(t *testing.T) { } }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "first": map[string]interface{}{ "theNumber": 1, @@ -160,20 +155,20 @@ func TestMutations_ExecutionOrdering_EvaluatesMutationsSerially(t *testing.T) { }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: mutationsTestSchema, AST: ast, Root: root, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestMutations_EvaluatesMutationsCorrectlyInThePresenceOfAFailedMutation(t *testing.T) { @@ -200,7 +195,7 @@ func TestMutations_EvaluatesMutationsCorrectlyInThePresenceOfAFailedMutation(t * } }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "first": map[string]interface{}{ "theNumber": 1, @@ -217,36 +212,36 @@ func TestMutations_EvaluatesMutationsCorrectlyInThePresenceOfAFailedMutation(t * }, "sixth": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Cannot change the number`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 8, Column: 7}, + Locations: []SourceLocation{ + SourceLocation{Line: 8, Column: 7}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: `Cannot change the number`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 17, Column: 7}, + Locations: []SourceLocation{ + SourceLocation{Line: 17, Column: 7}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: mutationsTestSchema, AST: ast, Root: root, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } t.Skipf("Testing equality for slice of errors in results") if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/executor/nonnull_test.go b/nonnull_test.go similarity index 56% rename from executor/nonnull_test.go rename to nonnull_test.go index 3a035803..bc53957b 100644 --- a/executor/nonnull_test.go +++ b/nonnull_test.go @@ -1,15 +1,9 @@ -package executor_test +package graphql import ( "reflect" "sort" "testing" - - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" ) var syncError = "sync" @@ -47,25 +41,25 @@ var nullingData = map[string]interface{}{ }, } -var dataType = types.NewObject(types.ObjectConfig{ +var dataType = NewObject(ObjectConfig{ Name: "DataType", - Fields: types.FieldConfigMap{ - "sync": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "sync": &FieldConfig{ + Type: String, }, - "nonNullSync": &types.FieldConfig{ - Type: types.NewNonNull(types.String), + "nonNullSync": &FieldConfig{ + Type: NewNonNull(String), }, - "promise": &types.FieldConfig{ - Type: types.String, + "promise": &FieldConfig{ + Type: String, }, - "nonNullPromise": &types.FieldConfig{ - Type: types.NewNonNull(types.String), + "nonNullPromise": &FieldConfig{ + Type: NewNonNull(String), }, }, }) -var nonNullTestSchema, _ = types.NewSchema(types.SchemaConfig{ +var nonNullTestSchema, _ = NewSchema(SchemaConfig{ Query: dataType, }) @@ -96,17 +90,17 @@ func init() { return nullingData } - dataType.AddFieldConfig("nest", &types.FieldConfig{ + dataType.AddFieldConfig("nest", &FieldConfig{ Type: dataType, }) - dataType.AddFieldConfig("nonNullNest", &types.FieldConfig{ - Type: types.NewNonNull(dataType), + dataType.AddFieldConfig("nonNullNest", &FieldConfig{ + Type: NewNonNull(dataType), }) - dataType.AddFieldConfig("promiseNest", &types.FieldConfig{ + dataType.AddFieldConfig("promiseNest", &FieldConfig{ Type: dataType, }) - dataType.AddFieldConfig("nonNullPromiseNest", &types.FieldConfig{ - Type: types.NewNonNull(dataType), + dataType.AddFieldConfig("nonNullPromiseNest", &FieldConfig{ + Type: NewNonNull(dataType), }) } @@ -117,15 +111,15 @@ func TestNonNull_NullsANullableFieldThatThrowsSynchronously(t *testing.T) { sync } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "sync": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: syncError, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 3, Column: 9, }, }, @@ -133,20 +127,20 @@ func TestNonNull_NullsANullableFieldThatThrowsSynchronously(t *testing.T) { }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsANullableFieldThatThrowsInAPromise(t *testing.T) { @@ -155,15 +149,15 @@ func TestNonNull_NullsANullableFieldThatThrowsInAPromise(t *testing.T) { promise } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "promise": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: promiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 3, Column: 9, }, }, @@ -171,20 +165,20 @@ func TestNonNull_NullsANullableFieldThatThrowsInAPromise(t *testing.T) { }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANullableFieldThatThrowsSynchronously(t *testing.T) { @@ -195,15 +189,15 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANullableFieldThat } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: nonNullSyncError, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 4, Column: 11, }, }, @@ -211,20 +205,20 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANullableFieldThat }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldThatThrowsInAPromise(t *testing.T) { @@ -235,15 +229,15 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: nonNullPromiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 4, Column: 11, }, }, @@ -251,20 +245,20 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldThatThrowsSynchronously(t *testing.T) { @@ -275,15 +269,15 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: nonNullSyncError, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 4, Column: 11, }, }, @@ -291,20 +285,20 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldThatThrowsInAPromise(t *testing.T) { @@ -315,15 +309,15 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: nonNullPromiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 4, Column: 11, }, }, @@ -331,20 +325,20 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -377,7 +371,7 @@ func TestNonNull_NullsAComplexTreeOfNullableFieldsThatThrow(t *testing.T) { } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "sync": nil, @@ -404,101 +398,101 @@ func TestNonNull_NullsAComplexTreeOfNullableFieldsThatThrow(t *testing.T) { }, }, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: syncError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 4, Column: 11}, + Locations: []SourceLocation{ + SourceLocation{Line: 4, Column: 11}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: syncError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 7, Column: 13}, + Locations: []SourceLocation{ + SourceLocation{Line: 7, Column: 13}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: syncError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 11, Column: 13}, + Locations: []SourceLocation{ + SourceLocation{Line: 11, Column: 13}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: syncError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 16, Column: 11}, + Locations: []SourceLocation{ + SourceLocation{Line: 16, Column: 11}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: syncError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 19, Column: 13}, + Locations: []SourceLocation{ + SourceLocation{Line: 19, Column: 13}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: syncError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 23, Column: 13}, + Locations: []SourceLocation{ + SourceLocation{Line: 23, Column: 13}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: promiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 5, Column: 11}, + Locations: []SourceLocation{ + SourceLocation{Line: 5, Column: 11}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: promiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 8, Column: 13}, + Locations: []SourceLocation{ + SourceLocation{Line: 8, Column: 13}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: promiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 12, Column: 13}, + Locations: []SourceLocation{ + SourceLocation{Line: 12, Column: 13}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: promiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 17, Column: 11}, + Locations: []SourceLocation{ + SourceLocation{Line: 17, Column: 11}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: promiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 20, Column: 13}, + Locations: []SourceLocation{ + SourceLocation{Line: 20, Column: 13}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: promiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 24, Column: 13}, + Locations: []SourceLocation{ + SourceLocation{Line: 24, Column: 13}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected.Data, result.Data) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Data, result.Data)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Data, result.Data)) } - sort.Sort(graphqlerrors.GQLFormattedErrorSlice(expected.Errors)) - sort.Sort(graphqlerrors.GQLFormattedErrorSlice(result.Errors)) + sort.Sort(GQLFormattedErrorSlice(expected.Errors)) + sort.Sort(GQLFormattedErrorSlice(result.Errors)) if !reflect.DeepEqual(expected.Errors, result.Errors) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Errors, result.Errors)) } } func TestNonNull_NullsTheFirstNullableObjectAfterAFieldThrowsInALongChainOfFieldsThatAreNonNull(t *testing.T) { @@ -550,60 +544,60 @@ func TestNonNull_NullsTheFirstNullableObjectAfterAFieldThrowsInALongChainOfField } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, "promiseNest": nil, "anotherNest": nil, "anotherPromiseNest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: nonNullSyncError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 8, Column: 19}, + Locations: []SourceLocation{ + SourceLocation{Line: 8, Column: 19}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: nonNullSyncError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 19, Column: 19}, + Locations: []SourceLocation{ + SourceLocation{Line: 19, Column: 19}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: nonNullPromiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 30, Column: 19}, + Locations: []SourceLocation{ + SourceLocation{Line: 30, Column: 19}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: nonNullPromiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 41, Column: 19}, + Locations: []SourceLocation{ + SourceLocation{Line: 41, Column: 19}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected.Data, result.Data) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Data, result.Data)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Data, result.Data)) } - sort.Sort(graphqlerrors.GQLFormattedErrorSlice(expected.Errors)) - sort.Sort(graphqlerrors.GQLFormattedErrorSlice(result.Errors)) + sort.Sort(GQLFormattedErrorSlice(expected.Errors)) + sort.Sort(GQLFormattedErrorSlice(result.Errors)) if !reflect.DeepEqual(expected.Errors, result.Errors) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Errors, result.Errors)) } } @@ -613,29 +607,29 @@ func TestNonNull_NullsANullableFieldThatSynchronouslyReturnsNull(t *testing.T) { sync } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "sync": nil, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected.Data, result.Data) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Data, result.Data)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Data, result.Data)) } if !reflect.DeepEqual(expected.Errors, result.Errors) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Errors, result.Errors)) } } func TestNonNull_NullsANullableFieldThatSynchronouslyReturnsNullInAPromise(t *testing.T) { @@ -644,29 +638,29 @@ func TestNonNull_NullsANullableFieldThatSynchronouslyReturnsNullInAPromise(t *te promise } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "promise": nil, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected.Data, result.Data) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Data, result.Data)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Data, result.Data)) } if !reflect.DeepEqual(expected.Errors, result.Errors) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Errors, result.Errors)) } } func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldThatReturnsNullSynchronously(t *testing.T) { @@ -677,34 +671,34 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 4, Column: 11}, + Locations: []SourceLocation{ + SourceLocation{Line: 4, Column: 11}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldThatReturnsNullInAPromise(t *testing.T) { @@ -715,34 +709,34 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 4, Column: 11}, + Locations: []SourceLocation{ + SourceLocation{Line: 4, Column: 11}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -754,34 +748,34 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 4, Column: 11}, + Locations: []SourceLocation{ + SourceLocation{Line: 4, Column: 11}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldThatReturnsNullInAPromise(t *testing.T) { @@ -792,34 +786,34 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 4, Column: 11}, + Locations: []SourceLocation{ + SourceLocation{Line: 4, Column: 11}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsAComplexTreeOfNullableFieldsThatReturnNull(t *testing.T) { @@ -851,7 +845,7 @@ func TestNonNull_NullsAComplexTreeOfNullableFieldsThatReturnNull(t *testing.T) { } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": map[string]interface{}{ "sync": nil, @@ -880,23 +874,23 @@ func TestNonNull_NullsAComplexTreeOfNullableFieldsThatReturnNull(t *testing.T) { }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected.Data, result.Data) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Data, result.Data)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Data, result.Data)) } if !reflect.DeepEqual(expected.Errors, result.Errors) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Errors, result.Errors)) } } func TestNonNull_NullsTheFirstNullableObjectAfterAFieldReturnsNullInALongChainOfFieldsThatAreNonNull(t *testing.T) { @@ -948,60 +942,60 @@ func TestNonNull_NullsTheFirstNullableObjectAfterAFieldReturnsNullInALongChainOf } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nest": nil, "promiseNest": nil, "anotherNest": nil, "anotherPromiseNest": nil, }, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 8, Column: 19}, + Locations: []SourceLocation{ + SourceLocation{Line: 8, Column: 19}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 19, Column: 19}, + Locations: []SourceLocation{ + SourceLocation{Line: 19, Column: 19}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 30, Column: 19}, + Locations: []SourceLocation{ + SourceLocation{Line: 30, Column: 19}, }, }, - graphqlerrors.FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 41, Column: 19}, + Locations: []SourceLocation{ + SourceLocation{Line: 41, Column: 19}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected.Data, result.Data) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Data, result.Data)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Data, result.Data)) } - sort.Sort(graphqlerrors.GQLFormattedErrorSlice(expected.Errors)) - sort.Sort(graphqlerrors.GQLFormattedErrorSlice(result.Errors)) + sort.Sort(GQLFormattedErrorSlice(expected.Errors)) + sort.Sort(GQLFormattedErrorSlice(result.Errors)) if !reflect.DeepEqual(expected.Errors, result.Errors) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Errors, result.Errors)) } } @@ -1009,127 +1003,127 @@ func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldThrows(t *testing.T) { doc := ` query Q { nonNullSync } ` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: nonNullSyncError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 2, Column: 17}, + Locations: []SourceLocation{ + SourceLocation{Line: 2, Column: 17}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldErrors(t *testing.T) { doc := ` query Q { nonNullPromise } ` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: nonNullPromiseError, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 2, Column: 17}, + Locations: []SourceLocation{ + SourceLocation{Line: 2, Column: 17}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: throwingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldReturnsNull(t *testing.T) { doc := ` query Q { nonNullSync } ` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 2, Column: 17}, + Locations: []SourceLocation{ + SourceLocation{Line: 2, Column: 17}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldResolvesNull(t *testing.T) { doc := ` query Q { nonNullPromise } ` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []location.SourceLocation{ - location.SourceLocation{Line: 2, Column: 17}, + Locations: []SourceLocation{ + SourceLocation{Line: 2, Column: 17}, }, }, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: nonNullTestSchema, AST: ast, Root: nullingData, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/language/parser/parser.go b/parser.go similarity index 64% rename from language/parser/parser.go rename to parser.go index c8de4335..d223f844 100644 --- a/language/parser/parser.go +++ b/parser.go @@ -1,12 +1,7 @@ -package parser +package graphql import ( "fmt" - - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/lexer" - "github.com/chris-ramon/graphql/language/source" ) type parseFn func(parser *Parser) (interface{}, error) @@ -22,21 +17,21 @@ type ParseParams struct { } type Parser struct { - LexToken lexer.Lexer - Source *source.Source + LexToken Lexer + Source *Source Options ParseOptions PrevEnd int - Token lexer.Token + Token Token } -func Parse(p ParseParams) (*ast.Document, error) { - var sourceObj *source.Source +func Parse(p ParseParams) (*AstDocument, error) { + var sourceObj *Source switch p.Source.(type) { - case *source.Source: - sourceObj = p.Source.(*source.Source) + case *Source: + sourceObj = p.Source.(*Source) default: body, _ := p.Source.(string) - sourceObj = source.NewSource(&source.Source{Body: body}) + sourceObj = NewSource(&Source{Body: body}) } parser, err := makeParser(sourceObj, p.Options) if err != nil { @@ -50,15 +45,15 @@ func Parse(p ParseParams) (*ast.Document, error) { } // TODO: test and expose parseValue as a public -func parseValue(p ParseParams) (ast.Value, error) { - var value ast.Value - var sourceObj *source.Source +func parseValue(p ParseParams) (Value, error) { + var value Value + var sourceObj *Source switch p.Source.(type) { - case *source.Source: - sourceObj = p.Source.(*source.Source) + case *Source: + sourceObj = p.Source.(*Source) default: body, _ := p.Source.(string) - sourceObj = source.NewSource(&source.Source{Body: body}) + sourceObj = NewSource(&Source{Body: body}) } parser, err := makeParser(sourceObj, p.Options) if err != nil { @@ -72,19 +67,19 @@ func parseValue(p ParseParams) (ast.Value, error) { } // Converts a name lex token into a name parse node. -func parseName(parser *Parser) (*ast.Name, error) { - token, err := expect(parser, lexer.TokenKind[lexer.NAME]) +func parseName(parser *Parser) (*AstName, error) { + token, err := expect(parser, TokenKind[NAME]) if err != nil { return nil, err } - return ast.NewName(&ast.Name{ + return NewAstName(&AstName{ Value: token.Value, Loc: loc(parser, token.Start), }), nil } -func makeParser(s *source.Source, opts ParseOptions) (*Parser, error) { - lexToken := lexer.Lex(s) +func makeParser(s *Source, opts ParseOptions) (*Parser, error) { + lexToken := Lex(s) token, err := lexToken(0) if err != nil { return &Parser{}, err @@ -98,22 +93,22 @@ func makeParser(s *source.Source, opts ParseOptions) (*Parser, error) { }, nil } -/* Implements the parsing rules in the Document section. */ +/* Implements the parsing rules in the AstDocument section. */ -func parseDocument(parser *Parser) (*ast.Document, error) { +func parseDocument(parser *Parser) (*AstDocument, error) { start := parser.Token.Start - var nodes []ast.Node + var nodes []Node for { - if skip(parser, lexer.TokenKind[lexer.EOF]) { + if skip(parser, TokenKind[EOF]) { break } - if peek(parser, lexer.TokenKind[lexer.BRACE_L]) { + if peek(parser, TokenKind[BRACE_L]) { node, err := parseOperationDefinition(parser) if err != nil { return nil, err } nodes = append(nodes, node) - } else if peek(parser, lexer.TokenKind[lexer.NAME]) { + } else if peek(parser, TokenKind[NAME]) { switch parser.Token.Value { case "query": fallthrough @@ -174,17 +169,17 @@ func parseDocument(parser *Parser) (*ast.Document, error) { } nodes = append(nodes, node) default: - if err := unexpected(parser, lexer.Token{}); err != nil { + if err := unexpected(parser, Token{}); err != nil { return nil, err } } } else { - if err := unexpected(parser, lexer.Token{}); err != nil { + if err := unexpected(parser, Token{}); err != nil { return nil, err } } } - return ast.NewDocument(&ast.Document{ + return NewAstDocument(&AstDocument{ Loc: loc(parser, start), Definitions: nodes, }), nil @@ -192,21 +187,21 @@ func parseDocument(parser *Parser) (*ast.Document, error) { /* Implements the parsing rules in the Operations section. */ -func parseOperationDefinition(parser *Parser) (*ast.OperationDefinition, error) { +func parseOperationDefinition(parser *Parser) (*AstOperationDefinition, error) { start := parser.Token.Start - if peek(parser, lexer.TokenKind[lexer.BRACE_L]) { + if peek(parser, TokenKind[BRACE_L]) { selectionSet, err := parseSelectionSet(parser) if err != nil { return nil, err } - return ast.NewOperationDefinition(&ast.OperationDefinition{ + return NewAstOperationDefinition(&AstOperationDefinition{ Operation: "query", - Directives: []*ast.Directive{}, + Directives: []*AstDirective{}, SelectionSet: selectionSet, Loc: loc(parser, start), }), nil } - operationToken, err := expect(parser, lexer.TokenKind[lexer.NAME]) + operationToken, err := expect(parser, TokenKind[NAME]) if err != nil { return nil, err } @@ -227,7 +222,7 @@ func parseOperationDefinition(parser *Parser) (*ast.OperationDefinition, error) if err != nil { return nil, err } - return ast.NewOperationDefinition(&ast.OperationDefinition{ + return NewAstOperationDefinition(&AstOperationDefinition{ Operation: operation, Name: name, VariableDefinitions: variableDefinitions, @@ -237,13 +232,13 @@ func parseOperationDefinition(parser *Parser) (*ast.OperationDefinition, error) }), nil } -func parseVariableDefinitions(parser *Parser) ([]*ast.VariableDefinition, error) { - variableDefinitions := []*ast.VariableDefinition{} - if peek(parser, lexer.TokenKind[lexer.PAREN_L]) { - vdefs, err := many(parser, lexer.TokenKind[lexer.PAREN_L], parseVariableDefinition, lexer.TokenKind[lexer.PAREN_R]) +func parseVariableDefinitions(parser *Parser) ([]*AstVariableDefinition, error) { + variableDefinitions := []*AstVariableDefinition{} + if peek(parser, TokenKind[PAREN_L]) { + vdefs, err := many(parser, TokenKind[PAREN_L], parseVariableDefinition, TokenKind[PAREN_R]) for _, vdef := range vdefs { if vdef != nil { - variableDefinitions = append(variableDefinitions, vdef.(*ast.VariableDefinition)) + variableDefinitions = append(variableDefinitions, vdef.(*AstVariableDefinition)) } } if err != nil { @@ -260,7 +255,7 @@ func parseVariableDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - _, err = expect(parser, lexer.TokenKind[lexer.COLON]) + _, err = expect(parser, TokenKind[COLON]) if err != nil { return nil, err } @@ -268,15 +263,15 @@ func parseVariableDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - var defaultValue ast.Value - if skip(parser, lexer.TokenKind[lexer.EQUALS]) { + var defaultValue Value + if skip(parser, TokenKind[EQUALS]) { dv, err := parseValueLiteral(parser, true) if err != nil { return nil, err } defaultValue = dv } - return ast.NewVariableDefinition(&ast.VariableDefinition{ + return NewAstVariableDefinition(&AstVariableDefinition{ Variable: variable, Type: ttype, DefaultValue: defaultValue, @@ -284,9 +279,9 @@ func parseVariableDefinition(parser *Parser) (interface{}, error) { }), nil } -func parseVariable(parser *Parser) (*ast.Variable, error) { +func parseVariable(parser *Parser) (*AstVariable, error) { start := parser.Token.Start - _, err := expect(parser, lexer.TokenKind[lexer.DOLLAR]) + _, err := expect(parser, TokenKind[DOLLAR]) if err != nil { return nil, err } @@ -294,34 +289,34 @@ func parseVariable(parser *Parser) (*ast.Variable, error) { if err != nil { return nil, err } - return ast.NewVariable(&ast.Variable{ + return NewAstVariable(&AstVariable{ Name: name, Loc: loc(parser, start), }), nil } -func parseSelectionSet(parser *Parser) (*ast.SelectionSet, error) { +func parseSelectionSet(parser *Parser) (*AstSelectionSet, error) { start := parser.Token.Start - iSelections, err := many(parser, lexer.TokenKind[lexer.BRACE_L], parseSelection, lexer.TokenKind[lexer.BRACE_R]) + iSelections, err := many(parser, TokenKind[BRACE_L], parseSelection, TokenKind[BRACE_R]) if err != nil { return nil, err } - selections := []ast.Selection{} + selections := []Selection{} for _, iSelection := range iSelections { if iSelection != nil { - // type assert interface{} into ast.Selection interface - selections = append(selections, iSelection.(ast.Selection)) + // type assert interface{} into Selection interface + selections = append(selections, iSelection.(Selection)) } } - return ast.NewSelectionSet(&ast.SelectionSet{ + return NewAstSelectionSet(&AstSelectionSet{ Selections: selections, Loc: loc(parser, start), }), nil } func parseSelection(parser *Parser) (interface{}, error) { - if peek(parser, lexer.TokenKind[lexer.SPREAD]) { + if peek(parser, TokenKind[SPREAD]) { r, err := parseFragment(parser) return r, err } else { @@ -329,17 +324,17 @@ func parseSelection(parser *Parser) (interface{}, error) { } } -func parseField(parser *Parser) (*ast.Field, error) { +func parseField(parser *Parser) (*AstField, error) { start := parser.Token.Start nameOrAlias, err := parseName(parser) if err != nil { return nil, err } var ( - name *ast.Name - alias *ast.Name + name *AstName + alias *AstName ) - if skip(parser, lexer.TokenKind[lexer.COLON]) { + if skip(parser, TokenKind[COLON]) { alias = nameOrAlias n, err := parseName(parser) if err != nil { @@ -357,15 +352,15 @@ func parseField(parser *Parser) (*ast.Field, error) { if err != nil { return nil, err } - var selectionSet *ast.SelectionSet - if peek(parser, lexer.TokenKind[lexer.BRACE_L]) { + var selectionSet *AstSelectionSet + if peek(parser, TokenKind[BRACE_L]) { sSet, err := parseSelectionSet(parser) if err != nil { return nil, err } selectionSet = sSet } - return ast.NewField(&ast.Field{ + return NewField(&AstField{ Alias: alias, Name: name, Arguments: arguments, @@ -375,16 +370,16 @@ func parseField(parser *Parser) (*ast.Field, error) { }), nil } -func parseArguments(parser *Parser) ([]*ast.Argument, error) { - arguments := []*ast.Argument{} - if peek(parser, lexer.TokenKind[lexer.PAREN_L]) { - iArguments, err := many(parser, lexer.TokenKind[lexer.PAREN_L], parseArgument, lexer.TokenKind[lexer.PAREN_R]) +func parseArguments(parser *Parser) ([]*AstArgument, error) { + arguments := []*AstArgument{} + if peek(parser, TokenKind[PAREN_L]) { + iArguments, err := many(parser, TokenKind[PAREN_L], parseArgument, TokenKind[PAREN_R]) if err != nil { return arguments, err } for _, iArgument := range iArguments { if iArgument != nil { - arguments = append(arguments, iArgument.(*ast.Argument)) + arguments = append(arguments, iArgument.(*AstArgument)) } } return arguments, nil @@ -398,7 +393,7 @@ func parseArgument(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - _, err = expect(parser, lexer.TokenKind[lexer.COLON]) + _, err = expect(parser, TokenKind[COLON]) if err != nil { return nil, err } @@ -406,7 +401,7 @@ func parseArgument(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return ast.NewArgument(&ast.Argument{ + return NewAstArgument(&AstArgument{ Name: name, Value: value, Loc: loc(parser, start), @@ -417,13 +412,13 @@ func parseArgument(parser *Parser) (interface{}, error) { func parseFragment(parser *Parser) (interface{}, error) { start := parser.Token.Start - _, err := expect(parser, lexer.TokenKind[lexer.SPREAD]) + _, err := expect(parser, TokenKind[SPREAD]) if err != nil { return nil, err } if parser.Token.Value == "on" { advance(parser) - name, err := parseNamedType(parser) + name, err := parseNamed(parser) if err != nil { return nil, err } @@ -435,7 +430,7 @@ func parseFragment(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return ast.NewInlineFragment(&ast.InlineFragment{ + return NewAstInlineFragment(&AstInlineFragment{ TypeCondition: name, Directives: directives, SelectionSet: selectionSet, @@ -450,14 +445,14 @@ func parseFragment(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return ast.NewFragmentSpread(&ast.FragmentSpread{ + return NewAstFragmentSpread(&AstFragmentSpread{ Name: name, Directives: directives, Loc: loc(parser, start), }), nil } -func parseFragmentDefinition(parser *Parser) (*ast.FragmentDefinition, error) { +func parseFragmentDefinition(parser *Parser) (*AstFragmentDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "fragment") if err != nil { @@ -471,7 +466,7 @@ func parseFragmentDefinition(parser *Parser) (*ast.FragmentDefinition, error) { if err != nil { return nil, err } - typeCondition, err := parseNamedType(parser) + typeCondition, err := parseNamed(parser) if err != nil { return nil, err } @@ -483,7 +478,7 @@ func parseFragmentDefinition(parser *Parser) (*ast.FragmentDefinition, error) { if err != nil { return nil, err } - return ast.NewFragmentDefinition(&ast.FragmentDefinition{ + return NewAstFragmentDefinition(&AstFragmentDefinition{ Name: name, TypeCondition: typeCondition, Directives: directives, @@ -492,64 +487,64 @@ func parseFragmentDefinition(parser *Parser) (*ast.FragmentDefinition, error) { }), nil } -func parseFragmentName(parser *Parser) (*ast.Name, error) { +func parseFragmentName(parser *Parser) (*AstName, error) { if parser.Token.Value == "on" { - return nil, unexpected(parser, lexer.Token{}) + return nil, unexpected(parser, Token{}) } return parseName(parser) } /* Implements the parsing rules in the Values section. */ -func parseValueLiteral(parser *Parser, isConst bool) (ast.Value, error) { +func parseValueLiteral(parser *Parser, isConst bool) (Value, error) { token := parser.Token switch token.Kind { - case lexer.TokenKind[lexer.BRACKET_L]: + case TokenKind[BRACKET_L]: return parseList(parser, isConst) - case lexer.TokenKind[lexer.BRACE_L]: + case TokenKind[BRACE_L]: return parseObject(parser, isConst) - case lexer.TokenKind[lexer.INT]: + case TokenKind[INT]: advance(parser) - return ast.NewIntValue(&ast.IntValue{ + return NewAstIntValue(&AstIntValue{ Value: token.Value, Loc: loc(parser, token.Start), }), nil - case lexer.TokenKind[lexer.FLOAT]: + case TokenKind[FLOAT]: advance(parser) - return ast.NewFloatValue(&ast.FloatValue{ + return NewAstFloatValue(&AstFloatValue{ Value: token.Value, Loc: loc(parser, token.Start), }), nil - case lexer.TokenKind[lexer.STRING]: + case TokenKind[STRING]: advance(parser) - return ast.NewStringValue(&ast.StringValue{ + return NewAstStringValue(&AstStringValue{ Value: token.Value, Loc: loc(parser, token.Start), }), nil - case lexer.TokenKind[lexer.NAME]: + case TokenKind[NAME]: if token.Value == "true" || token.Value == "false" { advance(parser) value := true if token.Value == "false" { value = false } - return ast.NewBooleanValue(&ast.BooleanValue{ + return NewAstBooleanValue(&AstBooleanValue{ Value: value, Loc: loc(parser, token.Start), }), nil } else if token.Value != "null" { advance(parser) - return ast.NewEnumValue(&ast.EnumValue{ + return NewAstEnumValue(&AstEnumValue{ Value: token.Value, Loc: loc(parser, token.Start), }), nil } - case lexer.TokenKind[lexer.DOLLAR]: + case TokenKind[DOLLAR]: if !isConst { return parseVariable(parser) } } - if err := unexpected(parser, lexer.Token{}); err != nil { + if err := unexpected(parser, Token{}); err != nil { return nil, err } return nil, nil @@ -567,7 +562,7 @@ func parseValueValue(parser *Parser) (interface{}, error) { return parseValueLiteral(parser, false) } -func parseList(parser *Parser, isConst bool) (*ast.ListValue, error) { +func parseList(parser *Parser, isConst bool) (*AstListValue, error) { start := parser.Token.Start var item parseFn if isConst { @@ -575,30 +570,30 @@ func parseList(parser *Parser, isConst bool) (*ast.ListValue, error) { } else { item = parseValueValue } - iValues, err := any(parser, lexer.TokenKind[lexer.BRACKET_L], item, lexer.TokenKind[lexer.BRACKET_R]) + iValues, err := any(parser, TokenKind[BRACKET_L], item, TokenKind[BRACKET_R]) if err != nil { return nil, err } - values := []ast.Value{} + values := []Value{} for _, iValue := range iValues { - values = append(values, iValue.(ast.Value)) + values = append(values, iValue.(Value)) } - return ast.NewListValue(&ast.ListValue{ + return NewAstListValue(&AstListValue{ Values: values, Loc: loc(parser, start), }), nil } -func parseObject(parser *Parser, isConst bool) (*ast.ObjectValue, error) { +func parseObject(parser *Parser, isConst bool) (*AstObjectValue, error) { start := parser.Token.Start - _, err := expect(parser, lexer.TokenKind[lexer.BRACE_L]) + _, err := expect(parser, TokenKind[BRACE_L]) if err != nil { return nil, err } - fields := []*ast.ObjectField{} + fields := []*AstObjectField{} fieldNames := map[string]bool{} for { - if skip(parser, lexer.TokenKind[lexer.BRACE_R]) { + if skip(parser, TokenKind[BRACE_R]) { break } field, fieldName, err := parseObjectField(parser, isConst, fieldNames) @@ -608,13 +603,13 @@ func parseObject(parser *Parser, isConst bool) (*ast.ObjectValue, error) { fieldNames[fieldName] = true fields = append(fields, field) } - return ast.NewObjectValue(&ast.ObjectValue{ + return NewAstObjectValue(&AstObjectValue{ Fields: fields, Loc: loc(parser, start), }), nil } -func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) (*ast.ObjectField, string, error) { +func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) (*AstObjectField, string, error) { start := parser.Token.Start name, err := parseName(parser) if err != nil { @@ -623,9 +618,9 @@ func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) fieldName := name.Value if _, ok := fieldNames[fieldName]; ok { descp := fmt.Sprintf("Duplicate input object field %v.", fieldName) - return nil, "", graphqlerrors.NewSyntaxError(parser.Source, start, descp) + return nil, "", NewSyntaxError(parser.Source, start, descp) } - _, err = expect(parser, lexer.TokenKind[lexer.COLON]) + _, err = expect(parser, TokenKind[COLON]) if err != nil { return nil, "", err } @@ -633,7 +628,7 @@ func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) if err != nil { return nil, "", err } - return ast.NewObjectField(&ast.ObjectField{ + return NewAstObjectField(&AstObjectField{ Name: name, Value: value, Loc: loc(parser, start), @@ -642,10 +637,10 @@ func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) /* Implements the parsing rules in the Directives section. */ -func parseDirectives(parser *Parser) ([]*ast.Directive, error) { - directives := []*ast.Directive{} +func parseDirectives(parser *Parser) ([]*AstDirective, error) { + directives := []*AstDirective{} for { - if !peek(parser, lexer.TokenKind[lexer.AT]) { + if !peek(parser, TokenKind[AT]) { break } directive, err := parseDirective(parser) @@ -657,9 +652,9 @@ func parseDirectives(parser *Parser) ([]*ast.Directive, error) { return directives, nil } -func parseDirective(parser *Parser) (*ast.Directive, error) { +func parseDirective(parser *Parser) (*AstDirective, error) { start := parser.Token.Start - _, err := expect(parser, lexer.TokenKind[lexer.AT]) + _, err := expect(parser, TokenKind[AT]) if err != nil { return nil, err } @@ -671,7 +666,7 @@ func parseDirective(parser *Parser) (*ast.Directive, error) { if err != nil { return nil, err } - return ast.NewDirective(&ast.Directive{ + return NewAstDirective(&AstDirective{ Name: name, Arguments: args, Loc: loc(parser, start), @@ -680,32 +675,32 @@ func parseDirective(parser *Parser) (*ast.Directive, error) { /* Implements the parsing rules in the Types section. */ -func parseType(parser *Parser) (ast.Type, error) { +func parseType(parser *Parser) (AstType, error) { start := parser.Token.Start - var ttype ast.Type - if skip(parser, lexer.TokenKind[lexer.BRACKET_L]) { + var ttype AstType + if skip(parser, TokenKind[BRACKET_L]) { t, err := parseType(parser) if err != nil { return t, err } ttype = t - _, err = expect(parser, lexer.TokenKind[lexer.BRACKET_R]) + _, err = expect(parser, TokenKind[BRACKET_R]) if err != nil { return ttype, err } - ttype = ast.NewListType(&ast.ListType{ + ttype = NewAstList(&AstList{ Type: ttype, Loc: loc(parser, start), }) } else { - name, err := parseNamedType(parser) + name, err := parseNamed(parser) if err != nil { return ttype, err } ttype = name } - if skip(parser, lexer.TokenKind[lexer.BANG]) { - ttype = ast.NewNonNullType(&ast.NonNullType{ + if skip(parser, TokenKind[BANG]) { + ttype = NewAstNonNull(&AstNonNull{ Type: ttype, Loc: loc(parser, start), }) @@ -714,13 +709,13 @@ func parseType(parser *Parser) (ast.Type, error) { return ttype, nil } -func parseNamedType(parser *Parser) (*ast.NamedType, error) { +func parseNamed(parser *Parser) (*AstNamed, error) { start := parser.Token.Start name, err := parseName(parser) if err != nil { return nil, err } - return ast.NewNamed(&ast.NamedType{ + return NewAstNamed(&AstNamed{ Name: name, Loc: loc(parser, start), }), nil @@ -728,7 +723,7 @@ func parseNamedType(parser *Parser) (*ast.NamedType, error) { /* Implements the parsing rules in the Type Definition section. */ -func parseObjectTypeDefinition(parser *Parser) (*ast.ObjectDefinition, error) { +func parseObjectTypeDefinition(parser *Parser) (*AstObjectDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "type") if err != nil { @@ -742,17 +737,17 @@ func parseObjectTypeDefinition(parser *Parser) (*ast.ObjectDefinition, error) { if err != nil { return nil, err } - iFields, err := any(parser, lexer.TokenKind[lexer.BRACE_L], parseFieldDefinition, lexer.TokenKind[lexer.BRACE_R]) + iFields, err := any(parser, TokenKind[BRACE_L], parseFieldDefinition, TokenKind[BRACE_R]) if err != nil { return nil, err } - fields := []*ast.FieldDefinition{} + fields := []*AstFieldDefinition{} for _, iField := range iFields { if iField != nil { - fields = append(fields, iField.(*ast.FieldDefinition)) + fields = append(fields, iField.(*AstFieldDefinition)) } } - return ast.NewObjectDefinition(&ast.ObjectDefinition{ + return NewAstObjectDefinition(&AstObjectDefinition{ Name: name, Loc: loc(parser, start), Interfaces: interfaces, @@ -760,17 +755,17 @@ func parseObjectTypeDefinition(parser *Parser) (*ast.ObjectDefinition, error) { }), nil } -func parseImplementsInterfaces(parser *Parser) ([]*ast.NamedType, error) { - types := []*ast.NamedType{} +func parseImplementsInterfaces(parser *Parser) ([]*AstNamed, error) { + types := []*AstNamed{} if parser.Token.Value == "implements" { advance(parser) for { - ttype, err := parseNamedType(parser) + ttype, err := parseNamed(parser) if err != nil { return types, err } types = append(types, ttype) - if peek(parser, lexer.TokenKind[lexer.BRACE_L]) { + if peek(parser, TokenKind[BRACE_L]) { break } } @@ -788,7 +783,7 @@ func parseFieldDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - _, err = expect(parser, lexer.TokenKind[lexer.COLON]) + _, err = expect(parser, TokenKind[COLON]) if err != nil { return nil, err } @@ -796,7 +791,7 @@ func parseFieldDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return ast.NewFieldDefinition(&ast.FieldDefinition{ + return NewAstFieldDefinition(&AstFieldDefinition{ Name: name, Arguments: args, Type: ttype, @@ -804,19 +799,19 @@ func parseFieldDefinition(parser *Parser) (interface{}, error) { }), nil } -func parseArgumentDefs(parser *Parser) ([]*ast.InputValueDefinition, error) { - inputValueDefinitions := []*ast.InputValueDefinition{} +func parseArgumentDefs(parser *Parser) ([]*AstInputValueDefinition, error) { + inputValueDefinitions := []*AstInputValueDefinition{} - if !peek(parser, lexer.TokenKind[lexer.PAREN_L]) { + if !peek(parser, TokenKind[PAREN_L]) { return inputValueDefinitions, nil } - iInputValueDefinitions, err := many(parser, lexer.TokenKind[lexer.PAREN_L], parseInputValueDef, lexer.TokenKind[lexer.PAREN_R]) + iInputValueDefinitions, err := many(parser, TokenKind[PAREN_L], parseInputValueDef, TokenKind[PAREN_R]) if err != nil { return inputValueDefinitions, err } for _, iInputValueDefinition := range iInputValueDefinitions { if iInputValueDefinition != nil { - inputValueDefinitions = append(inputValueDefinitions, iInputValueDefinition.(*ast.InputValueDefinition)) + inputValueDefinitions = append(inputValueDefinitions, iInputValueDefinition.(*AstInputValueDefinition)) } } return inputValueDefinitions, err @@ -828,7 +823,7 @@ func parseInputValueDef(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - _, err = expect(parser, lexer.TokenKind[lexer.COLON]) + _, err = expect(parser, TokenKind[COLON]) if err != nil { return nil, err } @@ -836,17 +831,17 @@ func parseInputValueDef(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - var defaultValue ast.Value - if skip(parser, lexer.TokenKind[lexer.EQUALS]) { + var defaultValue Value + if skip(parser, TokenKind[EQUALS]) { val, err := parseConstValue(parser) if err != nil { return nil, err } - if val, ok := val.(ast.Value); ok { + if val, ok := val.(Value); ok { defaultValue = val } } - return ast.NewInputValueDefinition(&ast.InputValueDefinition{ + return NewAstInputValueDefinition(&AstInputValueDefinition{ Name: name, Type: ttype, DefaultValue: defaultValue, @@ -854,7 +849,7 @@ func parseInputValueDef(parser *Parser) (interface{}, error) { }), nil } -func parseInterfaceTypeDefinition(parser *Parser) (*ast.InterfaceDefinition, error) { +func parseInterfaceTypeDefinition(parser *Parser) (*AstInterfaceDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "interface") if err != nil { @@ -864,24 +859,24 @@ func parseInterfaceTypeDefinition(parser *Parser) (*ast.InterfaceDefinition, err if err != nil { return nil, err } - iFields, err := any(parser, lexer.TokenKind[lexer.BRACE_L], parseFieldDefinition, lexer.TokenKind[lexer.BRACE_R]) + iFields, err := any(parser, TokenKind[BRACE_L], parseFieldDefinition, TokenKind[BRACE_R]) if err != nil { return nil, err } - fields := []*ast.FieldDefinition{} + fields := []*AstFieldDefinition{} for _, iField := range iFields { if iField != nil { - fields = append(fields, iField.(*ast.FieldDefinition)) + fields = append(fields, iField.(*AstFieldDefinition)) } } - return ast.NewInterfaceTypeDefinition(&ast.InterfaceDefinition{ + return NewAstInterfaceDefinition(&AstInterfaceDefinition{ Name: name, Loc: loc(parser, start), Fields: fields, }), nil } -func parseUnionTypeDefinition(parser *Parser) (*ast.UnionDefinition, error) { +func parseUnionTypeDefinition(parser *Parser) (*AstUnionDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "union") if err != nil { @@ -891,7 +886,7 @@ func parseUnionTypeDefinition(parser *Parser) (*ast.UnionDefinition, error) { if err != nil { return nil, err } - _, err = expect(parser, lexer.TokenKind[lexer.EQUALS]) + _, err = expect(parser, TokenKind[EQUALS]) if err != nil { return nil, err } @@ -899,29 +894,29 @@ func parseUnionTypeDefinition(parser *Parser) (*ast.UnionDefinition, error) { if err != nil { return nil, err } - return ast.NewUnionTypeDefinition(&ast.UnionDefinition{ + return NewAstUnionDefinition(&AstUnionDefinition{ Name: name, Loc: loc(parser, start), Types: types, }), nil } -func parseUnionMembers(parser *Parser) ([]*ast.NamedType, error) { - members := []*ast.NamedType{} +func parseUnionMembers(parser *Parser) ([]*AstNamed, error) { + members := []*AstNamed{} for { - member, err := parseNamedType(parser) + member, err := parseNamed(parser) if err != nil { return members, err } members = append(members, member) - if !skip(parser, lexer.TokenKind[lexer.PIPE]) { + if !skip(parser, TokenKind[PIPE]) { break } } return members, nil } -func parseScalarTypeDefinition(parser *Parser) (*ast.ScalarDefinition, error) { +func parseScalarTypeDefinition(parser *Parser) (*AstScalarDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "scalar") if err != nil { @@ -931,14 +926,14 @@ func parseScalarTypeDefinition(parser *Parser) (*ast.ScalarDefinition, error) { if err != nil { return nil, err } - def := ast.NewScalarTypeDefinition(&ast.ScalarDefinition{ + def := NewAstScalarDefinition(&AstScalarDefinition{ Name: name, Loc: loc(parser, start), }) return def, nil } -func parseEnumTypeDefinition(parser *Parser) (*ast.EnumDefinition, error) { +func parseEnumTypeDefinition(parser *Parser) (*AstEnumDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "enum") if err != nil { @@ -948,17 +943,17 @@ func parseEnumTypeDefinition(parser *Parser) (*ast.EnumDefinition, error) { if err != nil { return nil, err } - iEnumValueDefs, err := any(parser, lexer.TokenKind[lexer.BRACE_L], parseEnumValueDefinition, lexer.TokenKind[lexer.BRACE_R]) + iEnumValueDefs, err := any(parser, TokenKind[BRACE_L], parseEnumValueDefinition, TokenKind[BRACE_R]) if err != nil { return nil, err } - values := []*ast.EnumValueDefinition{} + values := []*AstEnumValueDefinition{} for _, iEnumValueDef := range iEnumValueDefs { if iEnumValueDef != nil { - values = append(values, iEnumValueDef.(*ast.EnumValueDefinition)) + values = append(values, iEnumValueDef.(*AstEnumValueDefinition)) } } - return ast.NewEnumTypeDefinition(&ast.EnumDefinition{ + return NewAstEnumDefinition(&AstEnumDefinition{ Name: name, Loc: loc(parser, start), Values: values, @@ -971,13 +966,13 @@ func parseEnumValueDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return ast.NewEnumValueDefinition(&ast.EnumValueDefinition{ + return NewAstEnumValueDefinition(&AstEnumValueDefinition{ Name: name, Loc: loc(parser, start), }), nil } -func parseInputObjectTypeDefinition(parser *Parser) (*ast.InputObjectDefinition, error) { +func parseInputObjectTypeDefinition(parser *Parser) (*AstInputObjectDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "input") if err != nil { @@ -987,24 +982,24 @@ func parseInputObjectTypeDefinition(parser *Parser) (*ast.InputObjectDefinition, if err != nil { return nil, err } - iInputValueDefinitions, err := any(parser, lexer.TokenKind[lexer.BRACE_L], parseInputValueDef, lexer.TokenKind[lexer.BRACE_R]) + iInputValueDefinitions, err := any(parser, TokenKind[BRACE_L], parseInputValueDef, TokenKind[BRACE_R]) if err != nil { return nil, err } - fields := []*ast.InputValueDefinition{} + fields := []*AstInputValueDefinition{} for _, iInputValueDefinition := range iInputValueDefinitions { if iInputValueDefinition != nil { - fields = append(fields, iInputValueDefinition.(*ast.InputValueDefinition)) + fields = append(fields, iInputValueDefinition.(*AstInputValueDefinition)) } } - return ast.NewInputObjectTypeDefinition(&ast.InputObjectDefinition{ + return NewAstInputObjectDefinition(&AstInputObjectDefinition{ Name: name, Loc: loc(parser, start), Fields: fields, }), nil } -func parseTypeExtensionDefinition(parser *Parser) (*ast.TypeExtensionDefinition, error) { +func parseTypeExtensionDefinition(parser *Parser) (*AstTypeExtensionDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "extend") if err != nil { @@ -1015,7 +1010,7 @@ func parseTypeExtensionDefinition(parser *Parser) (*ast.TypeExtensionDefinition, if err != nil { return nil, err } - return ast.NewTypeExtensionDefinition(&ast.TypeExtensionDefinition{ + return NewAstTypeExtensionDefinition(&AstTypeExtensionDefinition{ Loc: loc(parser, start), Definition: definition, }), nil @@ -1025,17 +1020,17 @@ func parseTypeExtensionDefinition(parser *Parser) (*ast.TypeExtensionDefinition, // Returns a location object, used to identify the place in // the source that created a given parsed object. -func loc(parser *Parser, start int) *ast.Location { +func loc(parser *Parser, start int) *AstLocation { if parser.Options.NoLocation { return nil } if parser.Options.NoSource { - return ast.NewLocation(&ast.Location{ + return NewAstLocation(&AstLocation{ Start: start, End: parser.PrevEnd, }) } - return ast.NewLocation(&ast.Location{ + return NewAstLocation(&AstLocation{ Start: start, End: parser.PrevEnd, Source: parser.Source, @@ -1072,39 +1067,39 @@ func skip(parser *Parser, Kind int) bool { // If the next token is of the given kind, return that token after advancing // the parser. Otherwise, do not change the parser state and return false. -func expect(parser *Parser, kind int) (lexer.Token, error) { +func expect(parser *Parser, kind int) (Token, error) { token := parser.Token if token.Kind == kind { advance(parser) return token, nil } - descp := fmt.Sprintf("Expected %s, found %s", lexer.GetTokenKindDesc(kind), lexer.GetTokenDesc(token)) - return token, graphqlerrors.NewSyntaxError(parser.Source, token.Start, descp) + descp := fmt.Sprintf("Expected %s, found %s", GetTokenKindDesc(kind), GetTokenDesc(token)) + return token, NewSyntaxError(parser.Source, token.Start, descp) } // If the next token is a keyword with the given value, return that token after // advancing the parser. Otherwise, do not change the parser state and return false. -func expectKeyWord(parser *Parser, value string) (lexer.Token, error) { +func expectKeyWord(parser *Parser, value string) (Token, error) { token := parser.Token - if token.Kind == lexer.TokenKind[lexer.NAME] && token.Value == value { + if token.Kind == TokenKind[NAME] && token.Value == value { advance(parser) return token, nil } - descp := fmt.Sprintf("Expected \"%s\", found %s", value, lexer.GetTokenDesc(token)) - return token, graphqlerrors.NewSyntaxError(parser.Source, token.Start, descp) + descp := fmt.Sprintf("Expected \"%s\", found %s", value, GetTokenDesc(token)) + return token, NewSyntaxError(parser.Source, token.Start, descp) } // Helper function for creating an error when an unexpected lexed token // is encountered. -func unexpected(parser *Parser, atToken lexer.Token) error { - var token lexer.Token - if (atToken == lexer.Token{}) { +func unexpected(parser *Parser, atToken Token) error { + var token Token + if (atToken == Token{}) { token = parser.Token } else { token = parser.Token } - description := fmt.Sprintf("Unexpected %v", lexer.GetTokenDesc(token)) - return graphqlerrors.NewSyntaxError(parser.Source, token.Start, description) + description := fmt.Sprintf("Unexpected %v", GetTokenDesc(token)) + return NewSyntaxError(parser.Source, token.Start, description) } // Returns a possibly empty list of parse nodes, determined by diff --git a/language/parser/parser_test.go b/parser_test.go similarity index 78% rename from language/parser/parser_test.go rename to parser_test.go index ec45324c..8f97a2e9 100644 --- a/language/parser/parser_test.go +++ b/parser_test.go @@ -1,17 +1,11 @@ -package parser +package graphql import ( - "reflect" - "testing" - "fmt" "io/ioutil" + "reflect" "strings" - - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/language/source" + "testing" ) func TestAcceptsOptionToNotIncludeSource(t *testing.T) { @@ -26,42 +20,42 @@ func TestAcceptsOptionToNotIncludeSource(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - oDef := ast.OperationDefinition{ + oDef := AstOperationDefinition{ Kind: "OperationDefinition", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 0, End: 9, }, Operation: "query", - Directives: []*ast.Directive{}, - SelectionSet: &ast.SelectionSet{ + Directives: []*AstDirective{}, + SelectionSet: &AstSelectionSet{ Kind: "SelectionSet", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 0, End: 9, }, - Selections: []ast.Selection{ - &ast.Field{ + Selections: []Selection{ + &AstField{ Kind: "Field", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 2, End: 7, }, - Name: &ast.Name{ + Name: &AstName{ Kind: "Name", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 2, End: 7, }, Value: "field", }, - Arguments: []*ast.Argument{}, - Directives: []*ast.Directive{}, + Arguments: []*AstArgument{}, + Directives: []*AstDirective{}, }, }, }, } - expectedDocument := ast.NewDocument(&ast.Document{ - Loc: &ast.Location{ + expectedDocument := NewAstDocument(&AstDocument{ + Loc: &AstLocation{ Start: 0, End: 9, }, - Definitions: []ast.Node{&oDef}, + Definitions: []Node{&oDef}, }) if !reflect.DeepEqual(document, expectedDocument) { t.Fatalf("unexpected document, expected: %v, got: %v", expectedDocument, document) @@ -78,14 +72,14 @@ func TestParseProvidesUsefulErrors(t *testing.T) { } _, err := Parse(params) - expectedError := &graphqlerrors.Error{ + expectedError := &Error{ Message: `Syntax Error GraphQL (1:2) Expected Name, found EOF 1: { ^ `, Positions: []int{1}, - Locations: []location.SourceLocation{{1, 2}}, + Locations: []SourceLocation{{1, 2}}, } checkError(t, err, expectedError) @@ -125,7 +119,7 @@ fragment MissingOn Type func TestParseProvidesUsefulErrorsWhenUsingSource(t *testing.T) { test := errorMessageTest{ - source.NewSource(&source.Source{Body: "query", Name: "MyQuery.graphql"}), + NewSource(&Source{Body: "query", Name: "MyQuery.graphql"}), `Syntax Error MyQuery.graphql (1:6) Expected Name, found EOF`, false, } @@ -248,7 +242,7 @@ func TestParseCreatesAst(t *testing.T) { } } ` - source := source.NewSource(&source.Source{Body: body}) + source := NewSource(&Source{Body: body}) document, err := Parse( ParseParams{ Source: source, @@ -261,90 +255,90 @@ func TestParseCreatesAst(t *testing.T) { t.Fatalf("unexpected error: %v", err) } - oDef := ast.OperationDefinition{ + oDef := AstOperationDefinition{ Kind: "OperationDefinition", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 0, End: 40, }, Operation: "query", - Directives: []*ast.Directive{}, - SelectionSet: &ast.SelectionSet{ + Directives: []*AstDirective{}, + SelectionSet: &AstSelectionSet{ Kind: "SelectionSet", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 0, End: 40, }, - Selections: []ast.Selection{ - &ast.Field{ + Selections: []Selection{ + &AstField{ Kind: "Field", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 4, End: 38, }, - Name: &ast.Name{ + Name: &AstName{ Kind: "Name", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 4, End: 8, }, Value: "node", }, - Arguments: []*ast.Argument{ + Arguments: []*AstArgument{ { Kind: "Argument", - Name: &ast.Name{ + Name: &AstName{ Kind: "Name", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 9, End: 11, }, Value: "id", }, - Value: &ast.IntValue{ + Value: &AstIntValue{ Kind: "IntValue", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 13, End: 14, }, Value: "4", }, - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 9, End: 14, }, }, }, - Directives: []*ast.Directive{}, - SelectionSet: &ast.SelectionSet{ + Directives: []*AstDirective{}, + SelectionSet: &AstSelectionSet{ Kind: "SelectionSet", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 16, End: 38, }, - Selections: []ast.Selection{ - &ast.Field{ + Selections: []Selection{ + &AstField{ Kind: "Field", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 22, End: 24, }, - Name: &ast.Name{ + Name: &AstName{ Kind: "Name", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 22, End: 24, }, Value: "id", }, - Arguments: []*ast.Argument{}, - Directives: []*ast.Directive{}, + Arguments: []*AstArgument{}, + Directives: []*AstDirective{}, SelectionSet: nil, }, - &ast.Field{ + &AstField{ Kind: "Field", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 30, End: 34, }, - Name: &ast.Name{ + Name: &AstName{ Kind: "Name", - Loc: &ast.Location{ + Loc: &AstLocation{ Start: 30, End: 34, }, Value: "name", }, - Arguments: []*ast.Argument{}, - Directives: []*ast.Directive{}, + Arguments: []*AstArgument{}, + Directives: []*AstDirective{}, SelectionSet: nil, }, }, @@ -353,14 +347,14 @@ func TestParseCreatesAst(t *testing.T) { }, }, } - expectedDocument := ast.NewDocument(&ast.Document{ - Loc: &ast.Location{ + expectedDocument := NewAstDocument(&AstDocument{ + Loc: &AstLocation{ Start: 0, End: 41, }, - Definitions: []ast.Node{&oDef}, + Definitions: []Node{&oDef}, }) if !reflect.DeepEqual(document, expectedDocument) { - t.Fatalf("unexpected document, expected: %v, got: %v", expectedDocument, document) + t.Fatalf("unexpected document, expected: %v, got: %v", expectedDocument, document.Definitions) } } @@ -379,7 +373,7 @@ func testErrorMessage(t *testing.T, test errorMessageTest) { checkErrorMessage(t, err, test.expectedMessage) } -func checkError(t *testing.T, err error, expectedError *graphqlerrors.Error) { +func checkError(t *testing.T, err error, expectedError *Error) { if expectedError == nil { if err != nil { t.Fatalf("unexpected error: %v", err) @@ -418,12 +412,12 @@ func checkErrorMessage(t *testing.T, err error, expectedMessage string) { } } -func toError(err error) *graphqlerrors.Error { +func toError(err error) *Error { if err == nil { return nil } switch err := err.(type) { - case *graphqlerrors.Error: + case *Error: return err default: return nil diff --git a/language/printer/printer.go b/printer.go similarity index 56% rename from language/printer/printer.go rename to printer.go index 0f04a483..1f55e301 100644 --- a/language/printer/printer.go +++ b/printer.go @@ -1,9 +1,7 @@ -package printer +package graphql import ( "fmt" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/visitor" "strings" ) @@ -102,30 +100,30 @@ func indent(maybeString interface{}) string { return "" } -var printDocASTReducer = map[string]visitor.VisitFunc{ - "Name": func(p visitor.VisitFuncParams) (string, interface{}) { +var printDocASTReducer = map[string]VisitFunc{ + "Name": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, getMapValue(node, "Value") + return ActionUpdate, getMapValue(node, "Value") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "Variable": func(p visitor.VisitFuncParams) (string, interface{}) { + "Variable": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, "$" + getMapValueString(node, "Name") + return ActionUpdate, "$" + getMapValueString(node, "Name") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "Document": func(p visitor.VisitFuncParams) (string, interface{}) { + "Document": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: definitions := toSliceString(getMapValue(node, "Definitions")) - return visitor.ActionUpdate, join(definitions, "\n\n") + "\n" + return ActionUpdate, join(definitions, "\n\n") + "\n" } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "OperationDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "OperationDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: op := getMapValueString(node, "Operation") @@ -145,11 +143,11 @@ var printDocASTReducer = map[string]visitor.VisitFunc{ selectionSet, }, " ") } - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "VariableDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "VariableDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: @@ -157,22 +155,22 @@ var printDocASTReducer = map[string]visitor.VisitFunc{ ttype := getMapValueString(node, "Type") defaultValue := getMapValueString(node, "DefaultValue") - return visitor.ActionUpdate, variable + ": " + ttype + wrap(" = ", defaultValue, "") + return ActionUpdate, variable + ": " + ttype + wrap(" = ", defaultValue, "") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "SelectionSet": func(p visitor.VisitFuncParams) (string, interface{}) { + "SelectionSet": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: selections := getMapValue(node, "Selections") str := block(selections) - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "Field": func(p visitor.VisitFuncParams) (string, interface{}) { + "Field": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: @@ -190,249 +188,249 @@ var printDocASTReducer = map[string]visitor.VisitFunc{ }, " ", ) - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "Argument": func(p visitor.VisitFuncParams) (string, interface{}) { + "Argument": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") value := getMapValueString(node, "Value") - return visitor.ActionUpdate, name + ": " + value + return ActionUpdate, name + ": " + value } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "FragmentSpread": func(p visitor.VisitFuncParams) (string, interface{}) { + "FragmentSpread": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") directives := toSliceString(getMapValue(node, "Directives")) - return visitor.ActionUpdate, "..." + name + wrap(" ", join(directives, " "), "") + return ActionUpdate, "..." + name + wrap(" ", join(directives, " "), "") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "InlineFragment": func(p visitor.VisitFuncParams) (string, interface{}) { + "InlineFragment": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: typeCondition := getMapValueString(node, "TypeCondition") directives := toSliceString(getMapValue(node, "Directives")) selectionSet := getMapValueString(node, "SelectionSet") - return visitor.ActionUpdate, "... on " + typeCondition + " " + wrap("", join(directives, " "), " ") + selectionSet + return ActionUpdate, "... on " + typeCondition + " " + wrap("", join(directives, " "), " ") + selectionSet } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "FragmentDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "FragmentDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") typeCondition := getMapValueString(node, "TypeCondition") directives := toSliceString(getMapValue(node, "Directives")) selectionSet := getMapValueString(node, "SelectionSet") - return visitor.ActionUpdate, "fragment " + name + " on " + typeCondition + " " + wrap("", join(directives, " "), " ") + selectionSet + return ActionUpdate, "fragment " + name + " on " + typeCondition + " " + wrap("", join(directives, " "), " ") + selectionSet } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "IntValue": func(p visitor.VisitFuncParams) (string, interface{}) { + "IntValue": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, getMapValueString(node, "Value") + return ActionUpdate, getMapValueString(node, "Value") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "FloatValue": func(p visitor.VisitFuncParams) (string, interface{}) { + "FloatValue": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, getMapValueString(node, "Value") + return ActionUpdate, getMapValueString(node, "Value") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "StringValue": func(p visitor.VisitFuncParams) (string, interface{}) { + "StringValue": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, `"` + getMapValueString(node, "Value") + `"` + return ActionUpdate, `"` + getMapValueString(node, "Value") + `"` } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "BooleanValue": func(p visitor.VisitFuncParams) (string, interface{}) { + "BooleanValue": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, getMapValueString(node, "Value") + return ActionUpdate, getMapValueString(node, "Value") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "EnumValue": func(p visitor.VisitFuncParams) (string, interface{}) { + "EnumValue": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, getMapValueString(node, "Value") + return ActionUpdate, getMapValueString(node, "Value") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "ListValue": func(p visitor.VisitFuncParams) (string, interface{}) { + "ListValue": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, "[" + join(toSliceString(getMapValue(node, "Values")), ", ") + "]" + return ActionUpdate, "[" + join(toSliceString(getMapValue(node, "Values")), ", ") + "]" } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "ObjectValue": func(p visitor.VisitFuncParams) (string, interface{}) { + "ObjectValue": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, "{" + join(toSliceString(getMapValue(node, "Fields")), ", ") + "}" + return ActionUpdate, "{" + join(toSliceString(getMapValue(node, "Fields")), ", ") + "}" } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "ObjectField": func(p visitor.VisitFuncParams) (string, interface{}) { + "ObjectField": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") value := getMapValueString(node, "Value") - return visitor.ActionUpdate, name + ": " + value + return ActionUpdate, name + ": " + value } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "Directive": func(p visitor.VisitFuncParams) (string, interface{}) { + "Directive": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") args := toSliceString(getMapValue(node, "Arguments")) - return visitor.ActionUpdate, "@" + name + wrap("(", join(args, ", "), ")") + return ActionUpdate, "@" + name + wrap("(", join(args, ", "), ")") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "NamedType": func(p visitor.VisitFuncParams) (string, interface{}) { + "Named": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, getMapValueString(node, "Name") + return ActionUpdate, getMapValueString(node, "Name") } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "ListType": func(p visitor.VisitFuncParams) (string, interface{}) { + "List": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, "[" + getMapValueString(node, "Type") + "]" + return ActionUpdate, "[" + getMapValueString(node, "Type") + "]" } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "NonNullType": func(p visitor.VisitFuncParams) (string, interface{}) { + "NonNull": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return visitor.ActionUpdate, getMapValueString(node, "Type") + "!" + return ActionUpdate, getMapValueString(node, "Type") + "!" } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "ObjectDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "ObjectDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") interfaces := toSliceString(getMapValue(node, "Interfaces")) fields := getMapValue(node, "Fields") str := "type " + name + " " + wrap("implements ", join(interfaces, ", "), " ") + block(fields) - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "FieldDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "FieldDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") ttype := getMapValueString(node, "Type") args := toSliceString(getMapValue(node, "Arguments")) str := name + wrap("(", join(args, ", "), ")") + ": " + ttype - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "InputValueDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "InputValueDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") ttype := getMapValueString(node, "Type") defaultValue := getMapValueString(node, "DefaultValue") str := name + ": " + ttype + wrap(" = ", defaultValue, "") - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "InterfaceDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "InterfaceDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") fields := getMapValue(node, "Fields") str := "interface " + name + " " + block(fields) - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "UnionDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "UnionDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") types := toSliceString(getMapValue(node, "Types")) str := "union " + name + " = " + join(types, " | ") - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "ScalarDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "ScalarDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") str := "scalar " + name - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "EnumDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "EnumDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") values := getMapValue(node, "Values") str := "enum " + name + " " + block(values) - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "EnumValueDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "EnumValueDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") - return visitor.ActionUpdate, name + return ActionUpdate, name } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "InputObjectDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "InputObjectDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") fields := getMapValue(node, "Fields") - return visitor.ActionUpdate, "input " + name + " " + block(fields) + return ActionUpdate, "input " + name + " " + block(fields) } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - "TypeExtensionDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { + "TypeExtensionDefinition": func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: definition := getMapValueString(node, "Definition") str := "extend " + definition - return visitor.ActionUpdate, str + return ActionUpdate, str } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, } -func Print(astNode ast.Node) (printed interface{}) { +func Print(astNode Node) (printed interface{}) { defer func() interface{} { if r := recover(); r != nil { return fmt.Sprintf("%v", astNode) } return printed }() - printed = visitor.Visit(astNode, &visitor.VisitorOptions{ + printed = Visit(astNode, &VisitorOptions{ LeaveKindMap: printDocASTReducer, }, nil) return printed diff --git a/language/printer/printer_test.go b/printer_test.go similarity index 56% rename from language/printer/printer_test.go rename to printer_test.go index 77d15f23..1de7f935 100644 --- a/language/printer/printer_test.go +++ b/printer_test.go @@ -1,19 +1,15 @@ -package printer_test +package graphql import ( - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/parser" - "github.com/chris-ramon/graphql/language/printer" - "github.com/chris-ramon/graphql/testutil" "io/ioutil" "reflect" "testing" ) -func parse(t *testing.T, query string) *ast.Document { - astDoc, err := parser.Parse(parser.ParseParams{ +func parse(t *testing.T, query string) *AstDocument { + astDoc, err := Parse(ParseParams{ Source: query, - Options: parser.ParseOptions{ + Options: ParseOptions{ NoLocation: true, }, }) @@ -24,7 +20,7 @@ func parse(t *testing.T, query string) *ast.Document { } func TestPrinter_DoesNotAlterAST(t *testing.T) { - b, err := ioutil.ReadFile("./../parser/kitchen-sink.graphql") + b, err := ioutil.ReadFile("./kitchen-sink.graphql") if err != nil { t.Fatalf("unable to load kitchen-sink.graphql") } @@ -32,34 +28,34 @@ func TestPrinter_DoesNotAlterAST(t *testing.T) { query := string(b) astDoc := parse(t, query) - astDocBefore := testutil.ASTToJSON(t, astDoc) + astDocBefore := ASTToJSON(t, astDoc) - _ = printer.Print(astDoc) + _ = Print(astDoc) - astDocAfter := testutil.ASTToJSON(t, astDoc) + astDocAfter := ASTToJSON(t, astDoc) - _ = testutil.ASTToJSON(t, astDoc) + _ = ASTToJSON(t, astDoc) if !reflect.DeepEqual(astDocAfter, astDocBefore) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(astDocAfter, astDocBefore)) + t.Fatalf("Unexpected result, Diff: %v", Diff(astDocAfter, astDocBefore)) } } func TestPrinter_PrintsMinimalAST(t *testing.T) { - astDoc := ast.NewField(&ast.Field{ - Name: ast.NewName(&ast.Name{ + astDoc := NewField(&AstField{ + Name: NewAstName(&AstName{ Value: "foo", }), }) - results := printer.Print(astDoc) + results := Print(astDoc) expected := "foo" if !reflect.DeepEqual(results, expected) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, results)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, results)) } } func TestPrinter_PrintsKitchenSink(t *testing.T) { - b, err := ioutil.ReadFile("./../parser/kitchen-sink.graphql") + b, err := ioutil.ReadFile("./kitchen-sink.graphql") if err != nil { t.Fatalf("unable to load kitchen-sink.graphql") } @@ -98,9 +94,9 @@ fragment frag on Follower { query } ` - results := printer.Print(astDoc) + results := Print(astDoc) if !reflect.DeepEqual(expected, results) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(results, expected)) + t.Fatalf("Unexpected result, Diff: %v", Diff(results, expected)) } } diff --git a/types/scalars.go b/scalars.go similarity index 85% rename from types/scalars.go rename to scalars.go index bec1b3b1..f42b5b37 100644 --- a/types/scalars.go +++ b/scalars.go @@ -1,10 +1,8 @@ -package types +package graphql import ( "fmt" "strconv" - - "github.com/chris-ramon/graphql/language/ast" ) var ( @@ -49,9 +47,9 @@ var Int *Scalar = NewScalar(ScalarConfig{ Name: "Int", Serialize: coerceInt, ParseValue: coerceInt, - ParseLiteral: func(valueAST ast.Value) interface{} { + ParseLiteral: func(valueAST Value) interface{} { switch valueAST := valueAST.(type) { - case *ast.IntValue: + case *AstIntValue: if intValue, err := strconv.Atoi(valueAST.Value); err == nil { return intValue } @@ -87,13 +85,13 @@ var Float *Scalar = NewScalar(ScalarConfig{ Name: "Float", Serialize: coerceFloat32, ParseValue: coerceFloat32, - ParseLiteral: func(valueAST ast.Value) interface{} { + ParseLiteral: func(valueAST Value) interface{} { switch valueAST := valueAST.(type) { - case *ast.FloatValue: + case *AstFloatValue: if floatValue, err := strconv.ParseFloat(valueAST.Value, 32); err == nil { return floatValue } - case *ast.IntValue: + case *AstIntValue: if floatValue, err := strconv.ParseFloat(valueAST.Value, 32); err == nil { return floatValue } @@ -110,9 +108,9 @@ var String *Scalar = NewScalar(ScalarConfig{ Name: "String", Serialize: coerceString, ParseValue: coerceString, - ParseLiteral: func(valueAST ast.Value) interface{} { + ParseLiteral: func(valueAST Value) interface{} { switch valueAST := valueAST.(type) { - case *ast.StringValue: + case *AstStringValue: return valueAST.Value } return "" @@ -152,9 +150,9 @@ var Boolean *Scalar = NewScalar(ScalarConfig{ Name: "Boolean", Serialize: coerceBool, ParseValue: coerceBool, - ParseLiteral: func(valueAST ast.Value) interface{} { + ParseLiteral: func(valueAST Value) interface{} { switch valueAST := valueAST.(type) { - case *ast.BooleanValue: + case *AstBooleanValue: return valueAST.Value } return false @@ -165,11 +163,11 @@ var ID *Scalar = NewScalar(ScalarConfig{ Name: "ID", Serialize: coerceString, ParseValue: coerceString, - ParseLiteral: func(valueAST ast.Value) interface{} { + ParseLiteral: func(valueAST Value) interface{} { switch valueAST := valueAST.(type) { - case *ast.IntValue: + case *AstIntValue: return valueAST.Value - case *ast.StringValue: + case *AstStringValue: return valueAST.Value } return "" diff --git a/types/scalars_serialization_test.go b/scalars_serialization_test.go similarity index 99% rename from types/scalars_serialization_test.go rename to scalars_serialization_test.go index 0d86f5d4..fde9d39b 100644 --- a/types/scalars_serialization_test.go +++ b/scalars_serialization_test.go @@ -1,4 +1,4 @@ -package types +package graphql import ( "reflect" diff --git a/language/parser/schema-kitchen-sink.graphql b/schema-kitchen-sink.graphql similarity index 100% rename from language/parser/schema-kitchen-sink.graphql rename to schema-kitchen-sink.graphql diff --git a/types/schema.go b/schema.go similarity index 99% rename from types/schema.go rename to schema.go index d834b830..dad5ebd6 100644 --- a/types/schema.go +++ b/schema.go @@ -1,4 +1,4 @@ -package types +package graphql import ( "fmt" diff --git a/schema_parser_test.go b/schema_parser_test.go new file mode 100644 index 00000000..75525134 --- /dev/null +++ b/schema_parser_test.go @@ -0,0 +1,754 @@ +package graphql + +import ( + "reflect" + "testing" +) + +func parsee(t *testing.T, query string) *AstDocument { + astDoc, err := Parse(ParseParams{ + Source: query, + Options: ParseOptions{ + NoLocation: false, + NoSource: true, + }, + }) + if err != nil { + t.Fatalf("Parse failed: %v", err) + } + return astDoc +} + +func testLoc(start int, end int) *AstLocation { + return &AstLocation{ + Start: start, End: end, + } +} +func TestSchemaParser_SimpleType(t *testing.T) { + + body := ` +type Hello { + world: String +}` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(1, 31), + Definitions: []Node{ + NewAstObjectDefinition(&AstObjectDefinition{ + Loc: testLoc(1, 31), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(6, 11), + }), + Interfaces: []*AstNamed{}, + Fields: []*AstFieldDefinition{ + NewAstFieldDefinition(&AstFieldDefinition{ + Loc: testLoc(16, 29), + Name: NewAstName(&AstName{ + Value: "world", + Loc: testLoc(16, 21), + }), + Arguments: []*AstInputValueDefinition{}, + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(23, 29), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(23, 29), + }), + }), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleExtension(t *testing.T) { + + body := ` +extend type Hello { + world: String +}` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(1, 38), + Definitions: []Node{ + NewAstTypeExtensionDefinition(&AstTypeExtensionDefinition{ + Loc: testLoc(1, 38), + Definition: NewAstObjectDefinition(&AstObjectDefinition{ + Loc: testLoc(8, 38), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(13, 18), + }), + Interfaces: []*AstNamed{}, + Fields: []*AstFieldDefinition{ + NewAstFieldDefinition(&AstFieldDefinition{ + Loc: testLoc(23, 36), + Name: NewAstName(&AstName{ + Value: "world", + Loc: testLoc(23, 28), + }), + Arguments: []*AstInputValueDefinition{}, + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(30, 36), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(30, 36), + }), + }), + }), + }, + }), + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleNonNullType(t *testing.T) { + + body := ` +type Hello { + world: String! +}` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(1, 32), + Definitions: []Node{ + NewAstObjectDefinition(&AstObjectDefinition{ + Loc: testLoc(1, 32), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(6, 11), + }), + Interfaces: []*AstNamed{}, + Fields: []*AstFieldDefinition{ + NewAstFieldDefinition(&AstFieldDefinition{ + Loc: testLoc(16, 30), + Name: NewAstName(&AstName{ + Value: "world", + Loc: testLoc(16, 21), + }), + Arguments: []*AstInputValueDefinition{}, + Type: NewAstNonNull(&AstNonNull{ + Kind: "NonNullType", + Loc: testLoc(23, 30), + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(23, 29), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(23, 29), + }), + }), + }), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleTypeInheritingInterface(t *testing.T) { + body := `type Hello implements World { }` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(0, 31), + Definitions: []Node{ + NewAstObjectDefinition(&AstObjectDefinition{ + Loc: testLoc(0, 31), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(5, 10), + }), + Interfaces: []*AstNamed{ + NewAstNamed(&AstNamed{ + Name: NewAstName(&AstName{ + Value: "World", + Loc: testLoc(22, 27), + }), + Loc: testLoc(22, 27), + }), + }, + Fields: []*AstFieldDefinition{}, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleTypeInheritingMultipleInterfaces(t *testing.T) { + body := `type Hello implements Wo, rld { }` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(0, 33), + Definitions: []Node{ + NewAstObjectDefinition(&AstObjectDefinition{ + Loc: testLoc(0, 33), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(5, 10), + }), + Interfaces: []*AstNamed{ + NewAstNamed(&AstNamed{ + Name: NewAstName(&AstName{ + Value: "Wo", + Loc: testLoc(22, 24), + }), + Loc: testLoc(22, 24), + }), + NewAstNamed(&AstNamed{ + Name: NewAstName(&AstName{ + Value: "rld", + Loc: testLoc(26, 29), + }), + Loc: testLoc(26, 29), + }), + }, + Fields: []*AstFieldDefinition{}, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SingleValueEnum(t *testing.T) { + body := `enum Hello { WORLD }` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(0, 20), + Definitions: []Node{ + NewAstEnumDefinition(&AstEnumDefinition{ + Loc: testLoc(0, 20), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(5, 10), + }), + Values: []*AstEnumValueDefinition{ + NewAstEnumValueDefinition(&AstEnumValueDefinition{ + Name: NewAstName(&AstName{ + Value: "WORLD", + Loc: testLoc(13, 18), + }), + Loc: testLoc(13, 18), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_DoubleValueEnum(t *testing.T) { + body := `enum Hello { WO, RLD }` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(0, 22), + Definitions: []Node{ + NewAstEnumDefinition(&AstEnumDefinition{ + Loc: testLoc(0, 22), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(5, 10), + }), + Values: []*AstEnumValueDefinition{ + NewAstEnumValueDefinition(&AstEnumValueDefinition{ + Name: NewAstName(&AstName{ + Value: "WO", + Loc: testLoc(13, 15), + }), + Loc: testLoc(13, 15), + }), + NewAstEnumValueDefinition(&AstEnumValueDefinition{ + Name: NewAstName(&AstName{ + Value: "RLD", + Loc: testLoc(17, 20), + }), + Loc: testLoc(17, 20), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleInterface(t *testing.T) { + body := ` +interface Hello { + world: String +}` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(1, 36), + Definitions: []Node{ + NewAstInterfaceDefinition(&AstInterfaceDefinition{ + Loc: testLoc(1, 36), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(11, 16), + }), + Fields: []*AstFieldDefinition{ + NewAstFieldDefinition(&AstFieldDefinition{ + Loc: testLoc(21, 34), + Name: NewAstName(&AstName{ + Value: "world", + Loc: testLoc(21, 26), + }), + Arguments: []*AstInputValueDefinition{}, + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(28, 34), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(28, 34), + }), + }), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleFieldWithArg(t *testing.T) { + body := ` +type Hello { + world(flag: Boolean): String +}` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(1, 46), + Definitions: []Node{ + NewAstObjectDefinition(&AstObjectDefinition{ + Loc: testLoc(1, 46), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(6, 11), + }), + Interfaces: []*AstNamed{}, + Fields: []*AstFieldDefinition{ + NewAstFieldDefinition(&AstFieldDefinition{ + Loc: testLoc(16, 44), + Name: NewAstName(&AstName{ + Value: "world", + Loc: testLoc(16, 21), + }), + Arguments: []*AstInputValueDefinition{ + NewAstInputValueDefinition(&AstInputValueDefinition{ + Loc: testLoc(22, 35), + Name: NewAstName(&AstName{ + Value: "flag", + Loc: testLoc(22, 26), + }), + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(28, 35), + Name: NewAstName(&AstName{ + Value: "Boolean", + Loc: testLoc(28, 35), + }), + }), + DefaultValue: nil, + }), + }, + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(38, 44), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(38, 44), + }), + }), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleFieldWithArgWithDefaultValue(t *testing.T) { + body := ` +type Hello { + world(flag: Boolean = true): String +}` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(1, 53), + Definitions: []Node{ + NewAstObjectDefinition(&AstObjectDefinition{ + Loc: testLoc(1, 53), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(6, 11), + }), + Interfaces: []*AstNamed{}, + Fields: []*AstFieldDefinition{ + NewAstFieldDefinition(&AstFieldDefinition{ + Loc: testLoc(16, 51), + Name: NewAstName(&AstName{ + Value: "world", + Loc: testLoc(16, 21), + }), + Arguments: []*AstInputValueDefinition{ + NewAstInputValueDefinition(&AstInputValueDefinition{ + Loc: testLoc(22, 42), + Name: NewAstName(&AstName{ + Value: "flag", + Loc: testLoc(22, 26), + }), + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(28, 35), + Name: NewAstName(&AstName{ + Value: "Boolean", + Loc: testLoc(28, 35), + }), + }), + DefaultValue: NewAstBooleanValue(&AstBooleanValue{ + Value: true, + Loc: testLoc(38, 42), + }), + }), + }, + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(45, 51), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(45, 51), + }), + }), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleFieldWithListArg(t *testing.T) { + body := ` +type Hello { + world(things: [String]): String +}` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(1, 49), + Definitions: []Node{ + NewAstObjectDefinition(&AstObjectDefinition{ + Loc: testLoc(1, 49), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(6, 11), + }), + Interfaces: []*AstNamed{}, + Fields: []*AstFieldDefinition{ + NewAstFieldDefinition(&AstFieldDefinition{ + Loc: testLoc(16, 47), + Name: NewAstName(&AstName{ + Value: "world", + Loc: testLoc(16, 21), + }), + Arguments: []*AstInputValueDefinition{ + NewAstInputValueDefinition(&AstInputValueDefinition{ + Loc: testLoc(22, 38), + Name: NewAstName(&AstName{ + Value: "things", + Loc: testLoc(22, 28), + }), + Type: NewAstList(&AstList{ + Loc: testLoc(30, 38), + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(31, 37), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(31, 37), + }), + }), + }), + DefaultValue: nil, + }), + }, + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(41, 47), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(41, 47), + }), + }), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleFieldWithTwoArg(t *testing.T) { + body := ` +type Hello { + world(argOne: Boolean, argTwo: Int): String +}` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(1, 61), + Definitions: []Node{ + NewAstObjectDefinition(&AstObjectDefinition{ + Loc: testLoc(1, 61), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(6, 11), + }), + Interfaces: []*AstNamed{}, + Fields: []*AstFieldDefinition{ + NewAstFieldDefinition(&AstFieldDefinition{ + Loc: testLoc(16, 59), + Name: NewAstName(&AstName{ + Value: "world", + Loc: testLoc(16, 21), + }), + Arguments: []*AstInputValueDefinition{ + NewAstInputValueDefinition(&AstInputValueDefinition{ + Loc: testLoc(22, 37), + Name: NewAstName(&AstName{ + Value: "argOne", + Loc: testLoc(22, 28), + }), + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(30, 37), + Name: NewAstName(&AstName{ + Value: "Boolean", + Loc: testLoc(30, 37), + }), + }), + DefaultValue: nil, + }), + NewAstInputValueDefinition(&AstInputValueDefinition{ + Loc: testLoc(39, 50), + Name: NewAstName(&AstName{ + Value: "argTwo", + Loc: testLoc(39, 45), + }), + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(47, 50), + Name: NewAstName(&AstName{ + Value: "Int", + Loc: testLoc(47, 50), + }), + }), + DefaultValue: nil, + }), + }, + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(53, 59), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(53, 59), + }), + }), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleUnion(t *testing.T) { + body := `union Hello = World` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(0, 19), + Definitions: []Node{ + NewAstUnionDefinition(&AstUnionDefinition{ + Loc: testLoc(0, 19), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(6, 11), + }), + Types: []*AstNamed{ + NewAstNamed(&AstNamed{ + Loc: testLoc(14, 19), + Name: NewAstName(&AstName{ + Value: "World", + Loc: testLoc(14, 19), + }), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_UnionWithTwoTypes(t *testing.T) { + body := `union Hello = Wo | Rld` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(0, 22), + Definitions: []Node{ + NewAstUnionDefinition(&AstUnionDefinition{ + Loc: testLoc(0, 22), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(6, 11), + }), + Types: []*AstNamed{ + NewAstNamed(&AstNamed{ + Loc: testLoc(14, 16), + Name: NewAstName(&AstName{ + Value: "Wo", + Loc: testLoc(14, 16), + }), + }), + NewAstNamed(&AstNamed{ + Loc: testLoc(19, 22), + Name: NewAstName(&AstName{ + Value: "Rld", + Loc: testLoc(19, 22), + }), + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_Scalar(t *testing.T) { + body := `scalar Hello` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(0, 12), + Definitions: []Node{ + NewAstScalarDefinition(&AstScalarDefinition{ + Loc: testLoc(0, 12), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(7, 12), + }), + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleInputObject(t *testing.T) { + body := ` +input Hello { + world: String +}` + astDoc := parsee(t, body) + expected := NewAstDocument(&AstDocument{ + Loc: testLoc(1, 32), + Definitions: []Node{ + NewAstInputObjectDefinition(&AstInputObjectDefinition{ + Loc: testLoc(1, 32), + Name: NewAstName(&AstName{ + Value: "Hello", + Loc: testLoc(7, 12), + }), + Fields: []*AstInputValueDefinition{ + NewAstInputValueDefinition(&AstInputValueDefinition{ + Loc: testLoc(17, 30), + Name: NewAstName(&AstName{ + Value: "world", + Loc: testLoc(17, 22), + }), + Type: NewAstNamed(&AstNamed{ + Loc: testLoc(24, 30), + Name: NewAstName(&AstName{ + Value: "String", + Loc: testLoc(24, 30), + }), + }), + DefaultValue: nil, + }), + }, + }), + }, + }) + if !reflect.DeepEqual(astDoc, expected) { + t.Fatalf("unexpected document, expected: %v, got: %v", expected, astDoc) + } +} + +func TestSchemaParser_SimpleInputObjectWithArgsShouldFail(t *testing.T) { + body := ` +input Hello { + world(foo: Int): String +}` + + _, err := Parse(ParseParams{ + Source: body, + Options: ParseOptions{ + NoLocation: false, + NoSource: true, + }, + }) + + expectedError := &Error{ + Message: `Syntax Error GraphQL (3:8) Expected :, found ( + +2: input Hello { +3: world(foo: Int): String + ^ +4: } +`, + Stack: `Syntax Error GraphQL (3:8) Expected :, found ( + +2: input Hello { +3: world(foo: Int): String + ^ +4: } +`, + Nodes: []Node{}, + Source: &Source{ + Body: ` +input Hello { + world(foo: Int): String +}`, + Name: "GraphQL", + }, + Positions: []int{22}, + Locations: []SourceLocation{ + {Line: 3, Column: 8}, + }, + } + if err == nil { + t.Fatalf("expected error, expected: %v, got: %v", expectedError, nil) + } + if !reflect.DeepEqual(expectedError, err) { + t.Fatalf("unexpected document, expected: %v, got: %v", expectedError, err) + } +} diff --git a/language/printer/schema_printer_test.go b/schema_printer_test.go similarity index 56% rename from language/printer/schema_printer_test.go rename to schema_printer_test.go index 4d91a10e..8c60113b 100644 --- a/language/printer/schema_printer_test.go +++ b/schema_printer_test.go @@ -1,57 +1,68 @@ -package printer_test +package graphql import ( - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/printer" - "github.com/chris-ramon/graphql/testutil" "io/ioutil" "reflect" "testing" ) +func parseee(t *testing.T, query string) *AstDocument { + astDoc, err := Parse(ParseParams{ + Source: query, + Options: ParseOptions{ + NoLocation: false, + NoSource: true, + }, + }) + if err != nil { + t.Fatalf("Parse failed: %v", err) + } + return astDoc +} + func TestSchemaPrinter_PrintsMinimalAST(t *testing.T) { - astDoc := ast.NewScalarTypeDefinition(&ast.ScalarDefinition{ - Name: ast.NewName(&ast.Name{ + astDoc := NewAstScalarDefinition(&AstScalarDefinition{ + Name: NewAstName(&AstName{ Value: "foo", }), }) - results := printer.Print(astDoc) + results := Print(astDoc) expected := "scalar foo" if !reflect.DeepEqual(results, expected) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, results)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, results)) } } func TestSchemaPrinter_DoesNotAlterAST(t *testing.T) { - b, err := ioutil.ReadFile("./../parser/schema-kitchen-sink.graphql") + b, err := ioutil.ReadFile("./schema-kitchen-sink.graphql") if err != nil { t.Fatalf("unable to load schema-kitchen-sink.graphql") } query := string(b) - astDoc := parse(t, query) + astDoc := parseee(t, query) - astDocBefore := testutil.ASTToJSON(t, astDoc) + astDocBefore := ASTToJSON(t, astDoc) - _ = printer.Print(astDoc) + _ = Print(astDoc) - astDocAfter := testutil.ASTToJSON(t, astDoc) + astDocAfter := ASTToJSON(t, astDoc) - _ = testutil.ASTToJSON(t, astDoc) + _ = ASTToJSON(t, astDoc) if !reflect.DeepEqual(astDocAfter, astDocBefore) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(astDocAfter, astDocBefore)) + t.Fatalf("Unexpected result, Diff: %v", Diff(astDocAfter, astDocBefore)) } } func TestSchemaPrinter_PrintsKitchenSink(t *testing.T) { - b, err := ioutil.ReadFile("./../parser/schema-kitchen-sink.graphql") + b, err := ioutil.ReadFile("./schema-kitchen-sink.graphql") if err != nil { t.Fatalf("unable to load schema-kitchen-sink.graphql") } query := string(b) - astDoc := parse(t, query) + astDoc := parseee(t, query) expected := `type Foo implements Bar { one: Type two(argument: InputType!): Type @@ -84,8 +95,8 @@ extend type Foo { seven(argument: [String]): Type } ` - results := printer.Print(astDoc) + results := Print(astDoc) if !reflect.DeepEqual(expected, results) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(results, expected)) + t.Fatalf("Unexpected result, Diff: %v", Diff(results, expected)) } } diff --git a/errors/sortutil.go b/sortutil.go similarity index 97% rename from errors/sortutil.go rename to sortutil.go index 03b8133c..2c237c0f 100644 --- a/errors/sortutil.go +++ b/sortutil.go @@ -1,4 +1,4 @@ -package graphqlerrors +package graphql import "bytes" diff --git a/language/source/source.go b/source.go similarity index 92% rename from language/source/source.go rename to source.go index c75192d4..85332839 100644 --- a/language/source/source.go +++ b/source.go @@ -1,4 +1,4 @@ -package source +package graphql const ( name = "GraphQL" diff --git a/errors/syntax.go b/syntax.go similarity index 71% rename from errors/syntax.go rename to syntax.go index 2c1fc548..0b9f2baa 100644 --- a/errors/syntax.go +++ b/syntax.go @@ -1,26 +1,22 @@ -package graphqlerrors +package graphql import ( "fmt" "regexp" - - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/language/source" ) -func NewSyntaxError(s *source.Source, position int, description string) *Error { - l := location.GetLocation(s, position) +func NewSyntaxError(s *Source, position int, description string) *Error { + l := GetLocation(s, position) return NewError( fmt.Sprintf("Syntax Error %s (%d:%d) %s\n\n%s", s.Name, l.Line, l.Column, description, highlightSourceAtLocation(s, l)), - []ast.Node{}, + []Node{}, "", s, []int{position}, ) } -func highlightSourceAtLocation(s *source.Source, l location.SourceLocation) string { +func highlightSourceAtLocation(s *Source, l SourceLocation) string { line := l.Line prevLineNum := fmt.Sprintf("%d", (line - 1)) lineNum := fmt.Sprintf("%d", line) diff --git a/testutil/testutil.go b/testutil.go similarity index 69% rename from testutil/testutil.go rename to testutil.go index f9bb706c..17b3324f 100644 --- a/testutil/testutil.go +++ b/testutil.go @@ -1,4 +1,4 @@ -package testutil +package graphql import ( "encoding/json" @@ -6,10 +6,6 @@ import ( "strconv" "testing" - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/parser" - "github.com/chris-ramon/graphql/types" "github.com/kr/pretty" ) @@ -23,10 +19,10 @@ var ( Artoo StarWarsChar HumanData map[int]StarWarsChar DroidData map[int]StarWarsChar - StarWarsSchema types.Schema + StarWarsSchema Schema - humanType *types.Object - droidType *types.Object + humanType *Object + droidType *Object ) type StarWarsChar struct { @@ -98,43 +94,43 @@ func init() { 2001: Artoo, } - episodeEnum := types.NewEnum(types.EnumConfig{ + episodeEnum := NewEnum(EnumConfig{ Name: "Episode", Description: "One of the films in the Star Wars Trilogy", - Values: types.EnumValueConfigMap{ - "NEWHOPE": &types.EnumValueConfig{ + Values: EnumValueConfigMap{ + "NEWHOPE": &EnumValueConfig{ Value: 4, Description: "Released in 1977.", }, - "EMPIRE": &types.EnumValueConfig{ + "EMPIRE": &EnumValueConfig{ Value: 5, Description: "Released in 1980.", }, - "JEDI": &types.EnumValueConfig{ + "JEDI": &EnumValueConfig{ Value: 6, Description: "Released in 1983.", }, }, }) - characterInterface := types.NewInterface(types.InterfaceConfig{ + characterInterface := NewInterface(InterfaceConfig{ Name: "Character", Description: "A character in the Star Wars Trilogy", - Fields: types.FieldConfigMap{ - "id": &types.FieldConfig{ - Type: types.NewNonNull(types.String), + Fields: FieldConfigMap{ + "id": &FieldConfig{ + Type: NewNonNull(String), Description: "The id of the character.", }, - "name": &types.FieldConfig{ - Type: types.String, + "name": &FieldConfig{ + Type: String, Description: "The name of the character.", }, - "appearsIn": &types.FieldConfig{ - Type: types.NewList(episodeEnum), + "appearsIn": &FieldConfig{ + Type: NewList(episodeEnum), Description: "Which movies they appear in.", }, }, - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { if character, ok := value.(StarWarsChar); ok { id, _ := strconv.Atoi(character.Id) human := GetHuman(id) @@ -145,59 +141,59 @@ func init() { return droidType }, }) - characterInterface.AddFieldConfig("friends", &types.FieldConfig{ - Type: types.NewList(characterInterface), + characterInterface.AddFieldConfig("friends", &FieldConfig{ + Type: NewList(characterInterface), Description: "The friends of the character, or an empty list if they have none.", }) - humanType = types.NewObject(types.ObjectConfig{ + humanType = NewObject(ObjectConfig{ Name: "Human", Description: "A humanoid creature in the Star Wars universe.", - Fields: types.FieldConfigMap{ - "id": &types.FieldConfig{ - Type: types.NewNonNull(types.String), + Fields: FieldConfigMap{ + "id": &FieldConfig{ + Type: NewNonNull(String), Description: "The id of the human.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { return human.Id } return nil }, }, - "name": &types.FieldConfig{ - Type: types.String, + "name": &FieldConfig{ + Type: String, Description: "The name of the human.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { return human.Name } return nil }, }, - "friends": &types.FieldConfig{ - Type: types.NewList(characterInterface), + "friends": &FieldConfig{ + Type: NewList(characterInterface), Description: "The friends of the human, or an empty list if they have none.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { return human.Friends } return []interface{}{} }, }, - "appearsIn": &types.FieldConfig{ - Type: types.NewList(episodeEnum), + "appearsIn": &FieldConfig{ + Type: NewList(episodeEnum), Description: "Which movies they appear in.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { return human.AppearsIn } return nil }, }, - "homePlanet": &types.FieldConfig{ - Type: types.String, + "homePlanet": &FieldConfig{ + Type: String, Description: "The home planet of the human, or null if unknown.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if human, ok := p.Source.(StarWarsChar); ok { return human.HomePlanet } @@ -205,38 +201,38 @@ func init() { }, }, }, - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ characterInterface, }, }) - droidType = types.NewObject(types.ObjectConfig{ + droidType = NewObject(ObjectConfig{ Name: "Droid", Description: "A mechanical creature in the Star Wars universe.", - Fields: types.FieldConfigMap{ - "id": &types.FieldConfig{ - Type: types.NewNonNull(types.String), + Fields: FieldConfigMap{ + "id": &FieldConfig{ + Type: NewNonNull(String), Description: "The id of the droid.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { return droid.Id } return nil }, }, - "name": &types.FieldConfig{ - Type: types.String, + "name": &FieldConfig{ + Type: String, Description: "The name of the droid.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { return droid.Name } return nil }, }, - "friends": &types.FieldConfig{ - Type: types.NewList(characterInterface), + "friends": &FieldConfig{ + Type: NewList(characterInterface), Description: "The friends of the droid, or an empty list if they have none.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { friends := []map[string]interface{}{} for _, friend := range droid.Friends { @@ -250,20 +246,20 @@ func init() { return []interface{}{} }, }, - "appearsIn": &types.FieldConfig{ - Type: types.NewList(episodeEnum), + "appearsIn": &FieldConfig{ + Type: NewList(episodeEnum), Description: "Which movies they appear in.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { return droid.AppearsIn } return nil }, }, - "primaryFunction": &types.FieldConfig{ - Type: types.String, + "primaryFunction": &FieldConfig{ + Type: String, Description: "The primary function of the droid.", - Resolve: func(p types.GQLFRParams) interface{} { + Resolve: func(p GQLFRParams) interface{} { if droid, ok := p.Source.(StarWarsChar); ok { return droid.PrimaryFunction } @@ -271,54 +267,54 @@ func init() { }, }, }, - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ characterInterface, }, }) - queryType := types.NewObject(types.ObjectConfig{ + queryType := NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "hero": &types.FieldConfig{ + Fields: FieldConfigMap{ + "hero": &FieldConfig{ Type: characterInterface, - Args: types.FieldConfigArgument{ - "episode": &types.ArgumentConfig{ + Args: FieldConfigArgument{ + "episode": &ArgumentConfig{ Description: "If omitted, returns the hero of the whole saga. If " + "provided, returns the hero of that particular episode.", Type: episodeEnum, }, }, - Resolve: func(p types.GQLFRParams) (r interface{}) { + Resolve: func(p GQLFRParams) (r interface{}) { return GetHero(p.Args["episode"]) }, }, - "human": &types.FieldConfig{ + "human": &FieldConfig{ Type: humanType, - Args: types.FieldConfigArgument{ - "id": &types.ArgumentConfig{ + Args: FieldConfigArgument{ + "id": &ArgumentConfig{ Description: "id of the human", - Type: types.NewNonNull(types.String), + Type: NewNonNull(String), }, }, - Resolve: func(p types.GQLFRParams) (r interface{}) { + Resolve: func(p GQLFRParams) (r interface{}) { return GetHuman(p.Args["id"].(int)) }, }, - "droid": &types.FieldConfig{ + "droid": &FieldConfig{ Type: droidType, - Args: types.FieldConfigArgument{ - "id": &types.ArgumentConfig{ + Args: FieldConfigArgument{ + "id": &ArgumentConfig{ Description: "id of the droid", - Type: types.NewNonNull(types.String), + Type: NewNonNull(String), }, }, - Resolve: func(p types.GQLFRParams) (r interface{}) { + Resolve: func(p GQLFRParams) (r interface{}) { return GetDroid(p.Args["id"].(int)) }, }, }, }) - StarWarsSchema, _ = types.NewSchema(types.SchemaConfig{ + StarWarsSchema, _ = NewSchema(SchemaConfig{ Query: queryType, }) } @@ -344,10 +340,10 @@ func GetHero(episode interface{}) interface{} { // Test helper functions -func Parse(t *testing.T, query string) *ast.Document { - astDoc, err := parser.Parse(parser.ParseParams{ +func TestParse(t *testing.T, query string) *AstDocument { + astDoc, err := Parse(ParseParams{ Source: query, - Options: parser.ParseOptions{ + Options: ParseOptions{ // include source, for error reporting NoSource: false, }, @@ -357,9 +353,9 @@ func Parse(t *testing.T, query string) *ast.Document { } return astDoc } -func Execute(t *testing.T, ep executor.ExecuteParams) *types.Result { - resultChannel := make(chan *types.Result) - go executor.Execute(ep, resultChannel) +func TestExecute(t *testing.T, ep ExecuteParams) *Result { + resultChannel := make(chan *Result) + go Execute(ep, resultChannel) result := <-resultChannel return result } @@ -368,15 +364,15 @@ func Diff(a, b interface{}) []string { return pretty.Diff(a, b) } -func ASTToJSON(t *testing.T, a ast.Node) interface{} { +func ASTToJSON(t *testing.T, a Node) interface{} { b, err := json.Marshal(a) if err != nil { - t.Fatalf("Failed to marshal ast.Node %v", err) + t.Fatalf("Failed to marshal Node %v", err) } var f interface{} err = json.Unmarshal(b, &f) if err != nil { - t.Fatalf("Failed to unmarshal ast.Node %v", err) + t.Fatalf("Failed to unmarshal Node %v", err) } return f } diff --git a/testutil/testutil_test.go b/testutil_test.go similarity index 88% rename from testutil/testutil_test.go rename to testutil_test.go index 4ce8ac01..754144d5 100644 --- a/testutil/testutil_test.go +++ b/testutil_test.go @@ -1,7 +1,6 @@ -package testutil_test +package graphql import ( - "github.com/chris-ramon/graphql/testutil" "testing" ) @@ -13,7 +12,7 @@ func TestSubsetSlice_Simple(t *testing.T) { sub := []interface{}{ "3", } - if !testutil.ContainSubsetSlice(super, sub) { + if !ContainSubsetSlice(super, sub) { t.Fatalf("expected slice to be subset of super, got false") } } @@ -25,7 +24,7 @@ func TestSubsetSlice_Simple_Fail(t *testing.T) { sub := []interface{}{ "4", } - if testutil.ContainSubsetSlice(super, sub) { + if ContainSubsetSlice(super, sub) { t.Fatalf("expected slice to not be subset of super, got true") } } @@ -53,7 +52,7 @@ func TestSubsetSlice_NestedSlice(t *testing.T) { "5", }, } - if !testutil.ContainSubsetSlice(super, sub) { + if !ContainSubsetSlice(super, sub) { t.Fatalf("expected slice to be subset of super, got false") } } @@ -78,7 +77,7 @@ func TestSubsetSlice_NestedSlice_DifferentLength(t *testing.T) { "6", }, } - if !testutil.ContainSubsetSlice(super, sub) { + if !ContainSubsetSlice(super, sub) { t.Fatalf("expected slice to be subset of super, got false") } } @@ -106,7 +105,7 @@ func TestSubsetSlice_NestedSlice_Fail(t *testing.T) { "9", }, } - if !testutil.ContainSubsetSlice(super, sub) { + if !ContainSubsetSlice(super, sub) { t.Fatalf("expected slice to be subset of super, got false") } } @@ -121,7 +120,7 @@ func TestSubset_Simple(t *testing.T) { sub := map[string]interface{}{ "c": "3", } - if !testutil.ContainSubset(super, sub) { + if !ContainSubset(super, sub) { t.Fatalf("expected map to be subset of super, got false") } @@ -136,7 +135,7 @@ func TestSubset_Simple_Fail(t *testing.T) { sub := map[string]interface{}{ "d": "3", } - if testutil.ContainSubset(super, sub) { + if ContainSubset(super, sub) { t.Fatalf("expected map to not be subset of super, got true") } @@ -159,7 +158,7 @@ func TestSubset_NestedMap(t *testing.T) { "cc": "33", }, } - if !testutil.ContainSubset(super, sub) { + if !ContainSubset(super, sub) { t.Fatalf("expected map to be subset of super, got false") } } @@ -181,7 +180,7 @@ func TestSubset_NestedMap_Fail(t *testing.T) { "dd": "44", }, } - if testutil.ContainSubset(super, sub) { + if ContainSubset(super, sub) { t.Fatalf("expected map to not be subset of super, got true") } } @@ -201,7 +200,7 @@ func TestSubset_NestedSlice(t *testing.T) { "11", }, } - if !testutil.ContainSubset(super, sub) { + if !ContainSubset(super, sub) { t.Fatalf("expected map to be subset of super, got false") } } @@ -250,7 +249,7 @@ func TestSubset_ComplexMixed(t *testing.T) { }, }, } - if !testutil.ContainSubset(super, sub) { + if !ContainSubset(super, sub) { t.Fatalf("expected map to be subset of super, got false") } } @@ -296,7 +295,7 @@ func TestSubset_ComplexMixed_Fail(t *testing.T) { }, }, } - if testutil.ContainSubset(super, sub) { + if ContainSubset(super, sub) { t.Fatalf("expected map to not be subset of super, got true") } } diff --git a/types.go b/types.go new file mode 100644 index 00000000..4d81df36 --- /dev/null +++ b/types.go @@ -0,0 +1,12 @@ +package graphql + +// type Schema interface{} + +type Result struct { + Data interface{} `json:"data"` + Errors []FormattedError `json:"errors,omitempty"` +} + +func (r *Result) HasErrors() bool { + return (len(r.Errors) > 0) +} diff --git a/types/types.go b/types/types.go deleted file mode 100644 index 36f66c5f..00000000 --- a/types/types.go +++ /dev/null @@ -1,16 +0,0 @@ -package types - -import ( - "github.com/chris-ramon/graphql/errors" -) - -// type Schema interface{} - -type Result struct { - Data interface{} `json:"data"` - Errors []graphqlerrors.FormattedError `json:"errors,omitempty"` -} - -func (gqR *Result) HasErrors() bool { - return (len(gqR.Errors) > 0) -} diff --git a/executor/union_interface_test.go b/union_interface_test.go similarity index 67% rename from executor/union_interface_test.go rename to union_interface_test.go index f397f734..d12f8d1e 100644 --- a/executor/union_interface_test.go +++ b/union_interface_test.go @@ -1,9 +1,6 @@ -package executor_test +package graphql import ( - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) @@ -28,56 +25,56 @@ type testPerson struct { Friends []testNamedType `json:"friends"` } -var namedType = types.NewInterface(types.InterfaceConfig{ +var namedType = NewInterface(InterfaceConfig{ Name: "Named", - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, }, }, }) -var dogType = types.NewObject(types.ObjectConfig{ +var dogType = NewObject(ObjectConfig{ Name: "Dog", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ namedType, }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, }, - "barks": &types.FieldConfig{ - Type: types.Boolean, + "barks": &FieldConfig{ + Type: Boolean, }, }, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testDog2) return ok }, }) -var catType = types.NewObject(types.ObjectConfig{ +var catType = NewObject(ObjectConfig{ Name: "Cat", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ namedType, }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, }, - "meows": &types.FieldConfig{ - Type: types.Boolean, + "meows": &FieldConfig{ + Type: Boolean, }, }, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testCat2) return ok }, }) -var petType = types.NewUnion(types.UnionConfig{ +var petType = NewUnion(UnionConfig{ Name: "Pet", - Types: []*types.Object{ + Types: []*Object{ dogType, catType, }, - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { if _, ok := value.(*testCat2); ok { return catType } @@ -87,29 +84,29 @@ var petType = types.NewUnion(types.UnionConfig{ return nil }, }) -var personType = types.NewObject(types.ObjectConfig{ +var personType = NewObject(ObjectConfig{ Name: "Person", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ namedType, }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, }, - "pets": &types.FieldConfig{ - Type: types.NewList(petType), + "pets": &FieldConfig{ + Type: NewList(petType), }, - "friends": &types.FieldConfig{ - Type: types.NewList(namedType), + "friends": &FieldConfig{ + Type: NewList(namedType), }, }, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { _, ok := value.(*testPerson) return ok }, }) -var unionInterfaceTestSchema, _ = types.NewSchema(types.SchemaConfig{ +var unionInterfaceTestSchema, _ = NewSchema(SchemaConfig{ Query: personType, }) @@ -151,7 +148,7 @@ func TestUnionIntersectionTypes_CanIntrospectOnUnionAndIntersectionTypes(t *test } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "Named": map[string]interface{}{ "kind": "INTERFACE", @@ -195,19 +192,19 @@ func TestUnionIntersectionTypes_CanIntrospectOnUnionAndIntersectionTypes(t *test }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: unionInterfaceTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestUnionIntersectionTypes_ExecutesUsingUnionTypes(t *testing.T) { @@ -224,7 +221,7 @@ func TestUnionIntersectionTypes_ExecutesUsingUnionTypes(t *testing.T) { } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -243,20 +240,20 @@ func TestUnionIntersectionTypes_ExecutesUsingUnionTypes(t *testing.T) { }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: unionInterfaceTestSchema, AST: ast, Root: john, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestUnionIntersectionTypes_ExecutesUnionTypesWithInlineFragments(t *testing.T) { @@ -278,7 +275,7 @@ func TestUnionIntersectionTypes_ExecutesUnionTypesWithInlineFragments(t *testing } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -297,20 +294,20 @@ func TestUnionIntersectionTypes_ExecutesUnionTypesWithInlineFragments(t *testing }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: unionInterfaceTestSchema, AST: ast, Root: john, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestUnionIntersectionTypes_ExecutesUsingInterfaceTypes(t *testing.T) { @@ -328,7 +325,7 @@ func TestUnionIntersectionTypes_ExecutesUsingInterfaceTypes(t *testing.T) { } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -346,20 +343,20 @@ func TestUnionIntersectionTypes_ExecutesUsingInterfaceTypes(t *testing.T) { }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: unionInterfaceTestSchema, AST: ast, Root: john, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestUnionIntersectionTypes_ExecutesInterfaceTypesWithInlineFragments(t *testing.T) { @@ -381,7 +378,7 @@ func TestUnionIntersectionTypes_ExecutesInterfaceTypesWithInlineFragments(t *tes } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -399,20 +396,20 @@ func TestUnionIntersectionTypes_ExecutesInterfaceTypesWithInlineFragments(t *tes }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: unionInterfaceTestSchema, AST: ast, Root: john, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -449,7 +446,7 @@ func TestUnionIntersectionTypes_AllowsFragmentConditionsToBeAbstractTypes(t *tes } } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "__typename": "Person", "name": "John", @@ -479,59 +476,59 @@ func TestUnionIntersectionTypes_AllowsFragmentConditionsToBeAbstractTypes(t *tes }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: unionInterfaceTestSchema, AST: ast, Root: john, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestUnionIntersectionTypes_GetsExecutionInfoInResolver(t *testing.T) { - var encounteredSchema *types.Schema + var encounteredSchema *Schema var encounteredRootValue interface{} - var personType2 *types.Object + var personType2 *Object - namedType2 := types.NewInterface(types.InterfaceConfig{ + namedType2 := NewInterface(InterfaceConfig{ Name: "Named", - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, }, }, - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { encounteredSchema = &info.Schema encounteredRootValue = info.RootValue return personType2 }, }) - personType2 = types.NewObject(types.ObjectConfig{ + personType2 = NewObject(ObjectConfig{ Name: "Person", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ namedType2, }, - Fields: types.FieldConfigMap{ - "name": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "name": &FieldConfig{ + Type: String, }, - "friends": &types.FieldConfig{ - Type: types.NewList(namedType2), + "friends": &FieldConfig{ + Type: NewList(namedType2), }, }, }) - schema2, _ := types.NewSchema(types.SchemaConfig{ + schema2, _ := NewSchema(SchemaConfig{ Query: personType2, }) @@ -543,7 +540,7 @@ func TestUnionIntersectionTypes_GetsExecutionInfoInResolver(t *testing.T) { } doc := `{ name, friends { name } }` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "name": "John", "friends": []interface{}{ @@ -554,19 +551,19 @@ func TestUnionIntersectionTypes_GetsExecutionInfoInResolver(t *testing.T) { }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: schema2, AST: ast, Root: john2, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/types/validation_test.go b/validation_test.go similarity index 56% rename from types/validation_test.go rename to validation_test.go index 266c3519..93b02de3 100644 --- a/types/validation_test.go +++ b/validation_test.go @@ -1,13 +1,10 @@ -package types_test +package graphql import ( "testing" - - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/types" ) -var someScalarType = types.NewScalar(types.ScalarConfig{ +var someScalarType = NewScalar(ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil @@ -15,115 +12,115 @@ var someScalarType = types.NewScalar(types.ScalarConfig{ ParseValue: func(value interface{}) interface{} { return nil }, - ParseLiteral: func(valueAST ast.Value) interface{} { + ParseLiteral: func(valueAST Value) interface{} { return nil }, }) -var someObjectType = types.NewObject(types.ObjectConfig{ +var someObjectType = NewObject(ObjectConfig{ Name: "SomeObject", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) -var objectWithIsTypeOf = types.NewObject(types.ObjectConfig{ +var objectWithIsTypeOf = NewObject(ObjectConfig{ Name: "ObjectWithIsTypeOf", - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { return true }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) -var someUnionType = types.NewUnion(types.UnionConfig{ +var someUnionType = NewUnion(UnionConfig{ Name: "SomeUnion", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Types: []*types.Object{ + Types: []*Object{ someObjectType, }, }) -var someInterfaceType = types.NewInterface(types.InterfaceConfig{ +var someInterfaceType = NewInterface(InterfaceConfig{ Name: "SomeInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) -var someEnumType = types.NewEnum(types.EnumConfig{ +var someEnumType = NewEnum(EnumConfig{ Name: "SomeEnum", - Values: types.EnumValueConfigMap{ - "ONLY": &types.EnumValueConfig{}, + Values: EnumValueConfigMap{ + "ONLY": &EnumValueConfig{}, }, }) -var someInputObject = types.NewInputObject(types.InputObjectConfig{ +var someInputObject = NewInputObject(InputObjectConfig{ Name: "SomeInputObject", - Fields: types.InputObjectConfigFieldMap{ - "f": &types.InputObjectFieldConfig{ - Type: types.String, + Fields: InputObjectConfigFieldMap{ + "f": &InputObjectFieldConfig{ + Type: String, DefaultValue: "Hello", }, }, }) -func withModifiers(ttypes []types.Type) []types.Type { +func withModifiers(ttypes []Type) []Type { res := ttypes for _, ttype := range ttypes { - res = append(res, types.NewList(ttype)) + res = append(res, NewList(ttype)) } for _, ttype := range ttypes { - res = append(res, types.NewNonNull(ttype)) + res = append(res, NewNonNull(ttype)) } for _, ttype := range ttypes { - res = append(res, types.NewNonNull(types.NewList(ttype))) + res = append(res, NewNonNull(NewList(ttype))) } return res } -var outputTypes = withModifiers([]types.Type{ - types.String, +var outputTypes = withModifiers([]Type{ + String, someScalarType, someEnumType, someObjectType, someUnionType, someInterfaceType, }) -var inputTypes = withModifiers([]types.Type{ - types.String, +var inputTypes = withModifiers([]Type{ + String, someScalarType, someEnumType, someInputObject, }) -func schemaWithFieldType(ttype types.Output) (types.Schema, error) { - return types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ +func schemaWithFieldType(ttype Output) (Schema, error) { + return NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ + Fields: FieldConfigMap{ + "f": &FieldConfig{ Type: ttype, }, }, }), }) } -func schemaWithInputObject(ttype types.Input) (types.Schema, error) { - return types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ +func schemaWithInputObject(ttype Input) (Schema, error) { + return NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "args": &types.ArgumentConfig{ + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "args": &ArgumentConfig{ Type: ttype, }, }, @@ -132,134 +129,134 @@ func schemaWithInputObject(ttype types.Input) (types.Schema, error) { }), }) } -func schemaWithObjectFieldOfType(fieldType types.Input) (types.Schema, error) { +func schemaWithObjectFieldOfType(fieldType Input) (Schema, error) { - badObjectType := types.NewObject(types.ObjectConfig{ + badObjectType := NewObject(ObjectConfig{ Name: "BadObject", - Fields: types.FieldConfigMap{ - "badField": &types.FieldConfig{ + Fields: FieldConfigMap{ + "badField": &FieldConfig{ Type: fieldType, }, }, }) - return types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + return NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ + Fields: FieldConfigMap{ + "f": &FieldConfig{ Type: badObjectType, }, }, }), }) } -func schemaWithObjectImplementingType(implementedType *types.Interface) (types.Schema, error) { +func schemaWithObjectImplementingType(implementedType *Interface) (Schema, error) { - badObjectType := types.NewObject(types.ObjectConfig{ + badObjectType := NewObject(ObjectConfig{ Name: "BadObject", - Interfaces: []*types.Interface{implementedType}, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Interfaces: []*Interface{implementedType}, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - return types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + return NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ + Fields: FieldConfigMap{ + "f": &FieldConfig{ Type: badObjectType, }, }, }), }) } -func schemaWithUnionOfType(ttype *types.Object) (types.Schema, error) { +func schemaWithUnionOfType(ttype *Object) (Schema, error) { - badObjectType := types.NewUnion(types.UnionConfig{ + badObjectType := NewUnion(UnionConfig{ Name: "BadUnion", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Types: []*types.Object{ttype}, + Types: []*Object{ttype}, }) - return types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + return NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ + Fields: FieldConfigMap{ + "f": &FieldConfig{ Type: badObjectType, }, }, }), }) } -func schemaWithInterfaceFieldOfType(ttype types.Type) (types.Schema, error) { +func schemaWithInterfaceFieldOfType(ttype Type) (Schema, error) { - badInterfaceType := types.NewInterface(types.InterfaceConfig{ + badInterfaceType := NewInterface(InterfaceConfig{ Name: "BadInterface", - Fields: types.FieldConfigMap{ - "badField": &types.FieldConfig{ + Fields: FieldConfigMap{ + "badField": &FieldConfig{ Type: ttype, }, }, }) - return types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + return NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ + Fields: FieldConfigMap{ + "f": &FieldConfig{ Type: badInterfaceType, }, }, }), }) } -func schemaWithArgOfType(ttype types.Type) (types.Schema, error) { +func schemaWithArgOfType(ttype Type) (Schema, error) { - badObject := types.NewObject(types.ObjectConfig{ + badObject := NewObject(ObjectConfig{ Name: "BadObject", - Fields: types.FieldConfigMap{ - "badField": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "badArg": &types.ArgumentConfig{ + Fields: FieldConfigMap{ + "badField": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "badArg": &ArgumentConfig{ Type: ttype, }, }, }, }, }) - return types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + return NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ + Fields: FieldConfigMap{ + "f": &FieldConfig{ Type: badObject, }, }, }), }) } -func schemaWithInputFieldOfType(ttype types.Type) (types.Schema, error) { +func schemaWithInputFieldOfType(ttype Type) (Schema, error) { - badInputObject := types.NewInputObject(types.InputObjectConfig{ + badInputObject := NewInputObject(InputObjectConfig{ Name: "BadInputObject", - Fields: types.InputObjectConfigFieldMap{ - "badField": &types.InputObjectFieldConfig{ + Fields: InputObjectConfigFieldMap{ + "badField": &InputObjectFieldConfig{ Type: ttype, }, }, }) - return types.NewSchema(types.SchemaConfig{ - Query: types.NewObject(types.ObjectConfig{ + return NewSchema(SchemaConfig{ + Query: NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "badArg": &types.ArgumentConfig{ + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "badArg": &ArgumentConfig{ Type: badInputObject, }, }, @@ -270,7 +267,7 @@ func schemaWithInputFieldOfType(ttype types.Type) (types.Schema, error) { } func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryTypeIsAnObjectType(t *testing.T) { - _, err := types.NewSchema(types.SchemaConfig{ + _, err := NewSchema(SchemaConfig{ Query: someObjectType, }) if err != nil { @@ -278,15 +275,15 @@ func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryTypeIs } } func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryAndMutationTypesAreObjectType(t *testing.T) { - mutationObject := types.NewObject(types.ObjectConfig{ + mutationObject := NewObject(ObjectConfig{ Name: "Mutation", - Fields: types.FieldConfigMap{ - "edit": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "edit": &FieldConfig{ + Type: String, }, }, }) - _, err := types.NewSchema(types.SchemaConfig{ + _, err := NewSchema(SchemaConfig{ Query: someObjectType, Mutation: mutationObject, }) @@ -295,7 +292,7 @@ func TestTypeSystem_SchemaMustHaveObjectRootTypes_AcceptsASchemaWhoseQueryAndMut } } func TestTypeSystem_SchemaMustHaveObjectRootTypes_RejectsASchemaWithoutAQueryType(t *testing.T) { - _, err := types.NewSchema(types.SchemaConfig{}) + _, err := NewSchema(SchemaConfig{}) expectedError := "Schema query must be Object Type but got: nil." if err == nil || err.Error() != expectedError { t.Fatalf("Expected error: %v, got %v", expectedError, err) @@ -304,24 +301,24 @@ func TestTypeSystem_SchemaMustHaveObjectRootTypes_RejectsASchemaWithoutAQueryTyp func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichRedefinesABuiltInType(t *testing.T) { - fakeString := types.NewScalar(types.ScalarConfig{ + fakeString := NewScalar(ScalarConfig{ Name: "String", Serialize: func(value interface{}) interface{} { return nil }, }) - queryType := types.NewObject(types.ObjectConfig{ + queryType := NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "normal": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "normal": &FieldConfig{ + Type: String, }, - "fake": &types.FieldConfig{ + "fake": &FieldConfig{ Type: fakeString, }, }, }) - _, err := types.NewSchema(types.SchemaConfig{ + _, err := NewSchema(SchemaConfig{ Query: queryType, }) expectedError := `Schema must contain unique named types but contains multiple types named "String".` @@ -331,34 +328,34 @@ func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichRedef } func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichDefinesAnObjectTypeTwice(t *testing.T) { - a := types.NewObject(types.ObjectConfig{ + a := NewObject(ObjectConfig{ Name: "SameName", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - b := types.NewObject(types.ObjectConfig{ + b := NewObject(ObjectConfig{ Name: "SameName", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - queryType := types.NewObject(types.ObjectConfig{ + queryType := NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "a": &types.FieldConfig{ + Fields: FieldConfigMap{ + "a": &FieldConfig{ Type: a, }, - "b": &types.FieldConfig{ + "b": &FieldConfig{ Type: b, }, }, }) - _, err := types.NewSchema(types.SchemaConfig{ + _, err := NewSchema(SchemaConfig{ Query: queryType, }) expectedError := `Schema must contain unique named types but contains multiple types named "SameName".` @@ -368,48 +365,48 @@ func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichDefin } func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichHaveSameNamedObjectsImplementingAnInterface(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - _ = types.NewObject(types.ObjectConfig{ + _ = NewObject(ObjectConfig{ Name: "BadObject", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ anotherInterface, }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - _ = types.NewObject(types.ObjectConfig{ + _ = NewObject(ObjectConfig{ Name: "BadObject", - Interfaces: []*types.Interface{ + Interfaces: []*Interface{ anotherInterface, }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - queryType := types.NewObject(types.ObjectConfig{ + queryType := NewObject(ObjectConfig{ Name: "Query", - Fields: types.FieldConfigMap{ - "iface": &types.FieldConfig{ + Fields: FieldConfigMap{ + "iface": &FieldConfig{ Type: anotherInterface, }, }, }) - _, err := types.NewSchema(types.SchemaConfig{ + _, err := NewSchema(SchemaConfig{ Query: queryType, }) expectedError := `Schema must contain unique named types but contains multiple types named "BadObject".` @@ -419,11 +416,11 @@ func TestTypeSystem_SchemaMustContainUniquelyNamedTypes_RejectsASchemaWhichHaveS } func TestTypeSystem_ObjectsMustHaveFields_AcceptsAnObjectTypeWithFieldsObject(t *testing.T) { - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "SomeObject", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, })) @@ -432,7 +429,7 @@ func TestTypeSystem_ObjectsMustHaveFields_AcceptsAnObjectTypeWithFieldsObject(t } } func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithMissingFields(t *testing.T) { - badObject := types.NewObject(types.ObjectConfig{ + badObject := NewObject(ObjectConfig{ Name: "SomeObject", }) _, err := schemaWithFieldType(badObject) @@ -442,11 +439,11 @@ func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithMissingFields(t } } func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithIncorrectlyNamedFields(t *testing.T) { - badObject := types.NewObject(types.ObjectConfig{ + badObject := NewObject(ObjectConfig{ Name: "SomeObject", - Fields: types.FieldConfigMap{ - "bad-name-with-dashes": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "bad-name-with-dashes": &FieldConfig{ + Type: String, }, }, }) @@ -457,9 +454,9 @@ func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithIncorrectlyName } } func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithEmptyFields(t *testing.T) { - badObject := types.NewObject(types.ObjectConfig{ + badObject := NewObject(ObjectConfig{ Name: "SomeObject", - Fields: types.FieldConfigMap{}, + Fields: FieldConfigMap{}, }) _, err := schemaWithFieldType(badObject) expectedError := `SomeObject fields must be an object with field names as keys or a function which return such an object.` @@ -469,14 +466,14 @@ func TestTypeSystem_ObjectsMustHaveFields_RejectsAnObjectTypeWithEmptyFields(t * } func TestTypeSystem_FieldsArgsMustBeProperlyNamed_AcceptsFieldArgsWithValidNames(t *testing.T) { - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "SomeObject", - Fields: types.FieldConfigMap{ - "goodField": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "goodArgs": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "goodField": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "goodArgs": &ArgumentConfig{ + Type: String, }, }, }, @@ -487,14 +484,14 @@ func TestTypeSystem_FieldsArgsMustBeProperlyNamed_AcceptsFieldArgsWithValidNames } } func TestTypeSystem_FieldsArgsMustBeProperlyNamed_RejectsFieldArgWithInvalidNames(t *testing.T) { - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "SomeObject", - Fields: types.FieldConfigMap{ - "badField": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "bad-name-with-dashes": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "badField": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "bad-name-with-dashes": &ArgumentConfig{ + Type: String, }, }, }, @@ -507,14 +504,14 @@ func TestTypeSystem_FieldsArgsMustBeProperlyNamed_RejectsFieldArgWithInvalidName } func TestTypeSystem_FieldsArgsMustBeObjects_AcceptsAnObjectTypeWithFieldArgs(t *testing.T) { - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "SomeObject", - Fields: types.FieldConfigMap{ - "goodField": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "goodArgs": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "goodField": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "goodArgs": &ArgumentConfig{ + Type: String, }, }, }, @@ -526,25 +523,25 @@ func TestTypeSystem_FieldsArgsMustBeObjects_AcceptsAnObjectTypeWithFieldArgs(t * } func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithArrayInterfaces(t *testing.T) { - anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ + anotherInterfaceType := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "SomeObject", - Interfaces: (types.InterfacesThunk)(func() []*types.Interface { - return []*types.Interface{anotherInterfaceType} + Interfaces: (InterfacesThunk)(func() []*Interface { + return []*Interface{anotherInterfaceType} }), - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, })) @@ -554,23 +551,23 @@ func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithArrayInte } func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithInterfacesAsFunctionReturningAnArray(t *testing.T) { - anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ + anotherInterfaceType := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "SomeObject", - Interfaces: []*types.Interface{anotherInterfaceType}, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Interfaces: []*Interface{anotherInterfaceType}, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, })) @@ -580,12 +577,12 @@ func TestTypeSystem_ObjectInterfacesMustBeArray_AcceptsAnObjectTypeWithInterface } func TestTypeSystem_UnionTypesMustBeArray_AcceptsAUnionTypeWithArrayTypes(t *testing.T) { - _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ + _, err := schemaWithFieldType(NewUnion(UnionConfig{ Name: "SomeUnion", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Types: []*types.Object{ + Types: []*Object{ someObjectType, }, })) @@ -594,9 +591,9 @@ func TestTypeSystem_UnionTypesMustBeArray_AcceptsAUnionTypeWithArrayTypes(t *tes } } func TestTypeSystem_UnionTypesMustBeArray_RejectsAUnionTypeWithoutTypes(t *testing.T) { - _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ + _, err := schemaWithFieldType(NewUnion(UnionConfig{ Name: "SomeUnion", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, })) @@ -606,12 +603,12 @@ func TestTypeSystem_UnionTypesMustBeArray_RejectsAUnionTypeWithoutTypes(t *testi } } func TestTypeSystem_UnionTypesMustBeArray_RejectsAUnionTypeWithEmptyTypes(t *testing.T) { - _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ + _, err := schemaWithFieldType(NewUnion(UnionConfig{ Name: "SomeUnion", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Types: []*types.Object{}, + Types: []*Object{}, })) expectedError := "Must provide Array of types for Union SomeUnion." if err == nil || err.Error() != expectedError { @@ -620,11 +617,11 @@ func TestTypeSystem_UnionTypesMustBeArray_RejectsAUnionTypeWithEmptyTypes(t *tes } func TestTypeSystem_InputObjectsMustHaveFields_AcceptsAnInputObjectTypeWithFields(t *testing.T) { - _, err := schemaWithInputObject(types.NewInputObject(types.InputObjectConfig{ + _, err := schemaWithInputObject(NewInputObject(InputObjectConfig{ Name: "SomeInputObject", - Fields: types.InputObjectConfigFieldMap{ - "f": &types.InputObjectFieldConfig{ - Type: types.String, + Fields: InputObjectConfigFieldMap{ + "f": &InputObjectFieldConfig{ + Type: String, }, }, })) @@ -634,12 +631,12 @@ func TestTypeSystem_InputObjectsMustHaveFields_AcceptsAnInputObjectTypeWithField } func TestTypeSystem_InputObjectsMustHaveFields_AcceptsAnInputObjectTypeWithAFieldFunction(t *testing.T) { - _, err := schemaWithInputObject(types.NewInputObject(types.InputObjectConfig{ + _, err := schemaWithInputObject(NewInputObject(InputObjectConfig{ Name: "SomeInputObject", - Fields: (types.InputObjectConfigFieldMapThunk)(func() types.InputObjectConfigFieldMap { - return types.InputObjectConfigFieldMap{ - "f": &types.InputObjectFieldConfig{ - Type: types.String, + Fields: (InputObjectConfigFieldMapThunk)(func() InputObjectConfigFieldMap { + return InputObjectConfigFieldMap{ + "f": &InputObjectFieldConfig{ + Type: String, }, } }), @@ -650,7 +647,7 @@ func TestTypeSystem_InputObjectsMustHaveFields_AcceptsAnInputObjectTypeWithAFiel } func TestTypeSystem_InputObjectsMustHaveFields_RejectsAnInputObjectTypeWithMissingFields(t *testing.T) { - _, err := schemaWithInputObject(types.NewInputObject(types.InputObjectConfig{ + _, err := schemaWithInputObject(NewInputObject(InputObjectConfig{ Name: "SomeInputObject", })) expectedError := "SomeInputObject fields must be an object with field names as keys or a function which return such an object." @@ -659,9 +656,9 @@ func TestTypeSystem_InputObjectsMustHaveFields_RejectsAnInputObjectTypeWithMissi } } func TestTypeSystem_InputObjectsMustHaveFields_RejectsAnInputObjectTypeWithEmptyFields(t *testing.T) { - _, err := schemaWithInputObject(types.NewInputObject(types.InputObjectConfig{ + _, err := schemaWithInputObject(NewInputObject(InputObjectConfig{ Name: "SomeInputObject", - Fields: types.InputObjectConfigFieldMap{}, + Fields: InputObjectConfigFieldMap{}, })) expectedError := "SomeInputObject fields must be an object with field names as keys or a function which return such an object." if err == nil || err.Error() != expectedError { @@ -670,14 +667,14 @@ func TestTypeSystem_InputObjectsMustHaveFields_RejectsAnInputObjectTypeWithEmpty } func TestTypeSystem_ObjectTypesMustBeAssertable_AcceptsAnObjectTypeWithAnIsTypeOfFunction(t *testing.T) { - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "AnotherObject", - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + IsTypeOf: func(value interface{}, info ResolveInfo) bool { return true }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, })) @@ -688,23 +685,23 @@ func TestTypeSystem_ObjectTypesMustBeAssertable_AcceptsAnObjectTypeWithAnIsTypeO func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefiningResolveType(t *testing.T) { - anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ + anotherInterfaceType := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "SomeObject", - Interfaces: []*types.Interface{anotherInterfaceType}, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Interfaces: []*Interface{anotherInterfaceType}, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, })) @@ -714,23 +711,23 @@ func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefinin } func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceWithImplementingTypeDefiningIsTypeOf(t *testing.T) { - anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ + anotherInterfaceType := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "SomeObject", - Interfaces: []*types.Interface{anotherInterfaceType}, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + Interfaces: []*Interface{anotherInterfaceType}, + IsTypeOf: func(value interface{}, info ResolveInfo) bool { return true }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, })) @@ -741,26 +738,26 @@ func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceWithImpleme func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefiningResolveTypeWithImplementingTypeDefiningIsTypeOf(t *testing.T) { - anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ + anotherInterfaceType := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) - _, err := schemaWithFieldType(types.NewObject(types.ObjectConfig{ + _, err := schemaWithFieldType(NewObject(ObjectConfig{ Name: "SomeObject", - Interfaces: []*types.Interface{anotherInterfaceType}, - IsTypeOf: func(value interface{}, info types.ResolveInfo) bool { + Interfaces: []*Interface{anotherInterfaceType}, + IsTypeOf: func(value interface{}, info ResolveInfo) bool { return true }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, })) @@ -771,10 +768,10 @@ func TestTypeSystem_InterfaceTypesMustBeResolvable_AcceptsAnInterfaceTypeDefinin func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionTypeDefiningResolveType(t *testing.T) { - _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ + _, err := schemaWithFieldType(NewUnion(UnionConfig{ Name: "SomeUnion", - Types: []*types.Object{someObjectType}, - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + Types: []*Object{someObjectType}, + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, })) @@ -784,9 +781,9 @@ func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionTypeDefiningResolveT } func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionOfObjectTypesDefiningIsTypeOf(t *testing.T) { - _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ + _, err := schemaWithFieldType(NewUnion(UnionConfig{ Name: "SomeUnion", - Types: []*types.Object{objectWithIsTypeOf}, + Types: []*Object{objectWithIsTypeOf}, })) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -794,10 +791,10 @@ func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionOfObjectTypesDefinin } func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionTypeDefiningResolveTypeOfObjectTypesDefiningIsTypeOf(t *testing.T) { - _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ + _, err := schemaWithFieldType(NewUnion(UnionConfig{ Name: "SomeUnion", - Types: []*types.Object{objectWithIsTypeOf}, - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + Types: []*Object{objectWithIsTypeOf}, + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, })) @@ -807,9 +804,9 @@ func TestTypeSystem_UnionTypesMustBeResolvable_AcceptsAUnionTypeDefiningResolveT } func TestTypeSystem_UnionTypesMustBeResolvable_RejectsAUnionTypeNotDefiningResolveTypeOfObjectTypesNotDefiningIsTypeOf(t *testing.T) { - _, err := schemaWithFieldType(types.NewUnion(types.UnionConfig{ + _, err := schemaWithFieldType(NewUnion(UnionConfig{ Name: "SomeUnion", - Types: []*types.Object{someObjectType}, + Types: []*Object{someObjectType}, })) expectedError := `Union Type SomeUnion does not provide a "resolveType" function and ` + `possible Type SomeObject does not provide a "isTypeOf" function. ` + @@ -821,7 +818,7 @@ func TestTypeSystem_UnionTypesMustBeResolvable_RejectsAUnionTypeNotDefiningResol func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningSerialize(t *testing.T) { - _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ + _, err := schemaWithFieldType(NewScalar(ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil @@ -833,7 +830,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningSeri } func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeNotDefiningSerialize(t *testing.T) { - _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ + _, err := schemaWithFieldType(NewScalar(ScalarConfig{ Name: "SomeScalar", })) expectedError := `SomeScalar must provide "serialize" function. If this custom Scalar ` + @@ -845,7 +842,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeNotDefiningS } func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningParseValueAndParseLiteral(t *testing.T) { - _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ + _, err := schemaWithFieldType(NewScalar(ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil @@ -853,7 +850,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningPars ParseValue: func(value interface{}) interface{} { return nil }, - ParseLiteral: func(valueAST ast.Value) interface{} { + ParseLiteral: func(valueAST Value) interface{} { return nil }, })) @@ -863,7 +860,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningPars } func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeDefiningParseValueButNotParseLiteral(t *testing.T) { - _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ + _, err := schemaWithFieldType(NewScalar(ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil @@ -879,12 +876,12 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeDefiningPars } func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeDefiningParseLiteralButNotParseValue(t *testing.T) { - _, err := schemaWithFieldType(types.NewScalar(types.ScalarConfig{ + _, err := schemaWithFieldType(NewScalar(ScalarConfig{ Name: "SomeScalar", Serialize: func(value interface{}) interface{} { return nil }, - ParseLiteral: func(valueAST ast.Value) interface{} { + ParseLiteral: func(valueAST Value) interface{} { return nil }, })) @@ -896,11 +893,11 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeDefiningPars func TestTypeSystem_EnumTypesMustBeWellDefined_AcceptsAWellDefinedEnumTypeWithEmptyValueDefinition(t *testing.T) { - _, err := schemaWithFieldType(types.NewEnum(types.EnumConfig{ + _, err := schemaWithFieldType(NewEnum(EnumConfig{ Name: "SomeEnum", - Values: types.EnumValueConfigMap{ - "FOO": &types.EnumValueConfig{}, - "BAR": &types.EnumValueConfig{}, + Values: EnumValueConfigMap{ + "FOO": &EnumValueConfig{}, + "BAR": &EnumValueConfig{}, }, })) if err != nil { @@ -909,13 +906,13 @@ func TestTypeSystem_EnumTypesMustBeWellDefined_AcceptsAWellDefinedEnumTypeWithEm } func TestTypeSystem_EnumTypesMustBeWellDefined_AcceptsAWellDefinedEnumTypeWithInternalValueDefinition(t *testing.T) { - _, err := schemaWithFieldType(types.NewEnum(types.EnumConfig{ + _, err := schemaWithFieldType(NewEnum(EnumConfig{ Name: "SomeEnum", - Values: types.EnumValueConfigMap{ - "FOO": &types.EnumValueConfig{ + Values: EnumValueConfigMap{ + "FOO": &EnumValueConfig{ Value: 10, }, - "BAR": &types.EnumValueConfig{ + "BAR": &EnumValueConfig{ Value: 20, }, }, @@ -926,7 +923,7 @@ func TestTypeSystem_EnumTypesMustBeWellDefined_AcceptsAWellDefinedEnumTypeWithIn } func TestTypeSystem_EnumTypesMustBeWellDefined_RejectsAnEnumTypeWithoutValues(t *testing.T) { - _, err := schemaWithFieldType(types.NewEnum(types.EnumConfig{ + _, err := schemaWithFieldType(NewEnum(EnumConfig{ Name: "SomeEnum", })) expectedError := `SomeEnum values must be an object with value names as keys.` @@ -936,9 +933,9 @@ func TestTypeSystem_EnumTypesMustBeWellDefined_RejectsAnEnumTypeWithoutValues(t } func TestTypeSystem_EnumTypesMustBeWellDefined_RejectsAnEnumTypeWithEmptyValues(t *testing.T) { - _, err := schemaWithFieldType(types.NewEnum(types.EnumConfig{ + _, err := schemaWithFieldType(NewEnum(EnumConfig{ Name: "SomeEnum", - Values: types.EnumValueConfigMap{}, + Values: EnumValueConfigMap{}, })) expectedError := `SomeEnum values must be an object with value names as keys.` if err == nil || err.Error() != expectedError { @@ -963,14 +960,14 @@ func TestTypeSystem_ObjectFieldsMustHaveOutputTypes_RejectsAnEmptyObjectFieldTyp } func TestTypeSystem_ObjectsCanOnlyImplementInterfaces_AcceptsAnObjectImplementingAnInterface(t *testing.T) { - anotherInterfaceType := types.NewInterface(types.InterfaceConfig{ + anotherInterfaceType := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "f": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "f": &FieldConfig{ + Type: String, }, }, }) @@ -1050,8 +1047,8 @@ func TestTypeSystem_InputObjectFieldsMustHaveInputTypes_RejectsAnEmptyInputField } func TestTypeSystem_ListMustAcceptGraphQLTypes_AcceptsAnTypeAsItemTypeOfList(t *testing.T) { - testTypes := withModifiers([]types.Type{ - types.String, + testTypes := withModifiers([]Type{ + String, someScalarType, someEnumType, someObjectType, @@ -1059,14 +1056,14 @@ func TestTypeSystem_ListMustAcceptGraphQLTypes_AcceptsAnTypeAsItemTypeOfList(t * someInterfaceType, }) for _, ttype := range testTypes { - result := types.NewList(ttype) + result := NewList(ttype) if result.GetError() != nil { t.Fatalf(`unexpected error: %v for type "%v"`, result.GetError(), ttype) } } } func TestTypeSystem_ListMustAcceptGraphQLTypes_RejectsANilTypeAsItemTypeOfList(t *testing.T) { - result := types.NewList(nil) + result := NewList(nil) expectedError := `Can only create List of a Type but got: .` if result.GetError() == nil || result.GetError().Error() != expectedError { t.Fatalf("Expected error: %v, got %v", expectedError, result.GetError()) @@ -1074,26 +1071,26 @@ func TestTypeSystem_ListMustAcceptGraphQLTypes_RejectsANilTypeAsItemTypeOfList(t } func TestTypeSystem_NonNullMustAcceptGraphQLTypes_AcceptsAnTypeAsNullableTypeOfNonNull(t *testing.T) { - nullableTypes := []types.Type{ - types.String, + nullableTypes := []Type{ + String, someScalarType, someObjectType, someUnionType, someInterfaceType, someEnumType, someInputObject, - types.NewList(types.String), - types.NewList(types.NewNonNull(types.String)), + NewList(String), + NewList(NewNonNull(String)), } for _, ttype := range nullableTypes { - result := types.NewNonNull(ttype) + result := NewNonNull(ttype) if result.GetError() != nil { t.Fatalf(`unexpected error: %v for type "%v"`, result.GetError(), ttype) } } } func TestTypeSystem_NonNullMustAcceptGraphQLTypes_RejectsNilAsNonNullableType(t *testing.T) { - result := types.NewNonNull(nil) + result := NewNonNull(nil) expectedError := `Can only create NonNull of a Nullable Type but got: .` if result.GetError() == nil || result.GetError().Error() != expectedError { t.Fatalf("Expected error: %v, got %v", expectedError, result.GetError()) @@ -1101,31 +1098,31 @@ func TestTypeSystem_NonNullMustAcceptGraphQLTypes_RejectsNilAsNonNullableType(t } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWhichImplementsAnInterface(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, }, }) - anotherObject := types.NewObject(types.ObjectConfig{ + anotherObject := NewObject(ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.Interface{anotherInterface}, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Interfaces: []*Interface{anotherInterface}, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, @@ -1137,36 +1134,36 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWhi } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWhichImplementsAnInterfaceAlongWithMoreFields(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, }, }) - anotherObject := types.NewObject(types.ObjectConfig{ + anotherObject := NewObject(ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.Interface{anotherInterface}, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Interfaces: []*Interface{anotherInterface}, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, - "anotherfield": &types.FieldConfig{ - Type: types.String, + "anotherfield": &FieldConfig{ + Type: String, }, }, }) @@ -1176,34 +1173,34 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWhi } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWhichImplementsAnInterfaceFieldAlongWithMoreArguments(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, }, }) - anotherObject := types.NewObject(types.ObjectConfig{ + anotherObject := NewObject(ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.Interface{anotherInterface}, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Interfaces: []*Interface{anotherInterface}, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, - "anotherInput": &types.ArgumentConfig{ - Type: types.String, + "anotherInput": &ArgumentConfig{ + Type: String, }, }, }, @@ -1216,28 +1213,28 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWhi } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMissingAnInterfaceField(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, }, }) - anotherObject := types.NewObject(types.ObjectConfig{ + anotherObject := NewObject(ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.Interface{anotherInterface}, - Fields: types.FieldConfigMap{ - "anotherfield": &types.FieldConfig{ - Type: types.String, + Interfaces: []*Interface{anotherInterface}, + Fields: FieldConfigMap{ + "anotherfield": &FieldConfig{ + Type: String, }, }, }) @@ -1248,31 +1245,31 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMis } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithAnIncorrectlyTypedInterfaceField(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, }, }) - anotherObject := types.NewObject(types.ObjectConfig{ + anotherObject := NewObject(ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.Interface{anotherInterface}, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ + Interfaces: []*Interface{anotherInterface}, + Fields: FieldConfigMap{ + "field": &FieldConfig{ Type: someScalarType, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, @@ -1285,28 +1282,28 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWit } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMissingAnInterfaceArgument(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, }, }) - anotherObject := types.NewObject(types.ObjectConfig{ + anotherObject := NewObject(ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.Interface{anotherInterface}, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, + Interfaces: []*Interface{anotherInterface}, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, }, }, }) @@ -1317,30 +1314,30 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectMis } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithAnIncorrectlyTypedInterfaceArgument(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, }, }, }) - anotherObject := types.NewObject(types.ObjectConfig{ + anotherObject := NewObject(ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.Interface{anotherInterface}, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ + Interfaces: []*Interface{anotherInterface}, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ Type: someScalarType, }, }, @@ -1354,23 +1351,23 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWit } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWithAnEquivalentlyModifiedInterfaceField(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.NewNonNull(types.NewList(types.String)), + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: NewNonNull(NewList(String)), }, }, }) - anotherObject := types.NewObject(types.ObjectConfig{ + anotherObject := NewObject(ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.Interface{anotherInterface}, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.NewNonNull(types.NewList(types.String)), + Interfaces: []*Interface{anotherInterface}, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: NewNonNull(NewList(String)), }, }, }) @@ -1380,23 +1377,23 @@ func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_AcceptsAnObjectWit } } func TestTypeSystem_ObjectsMustAdhereToInterfaceTheyImplement_RejectsAnObjectWithADifferentlyModifiedInterfaceFieldType(t *testing.T) { - anotherInterface := types.NewInterface(types.InterfaceConfig{ + anotherInterface := NewInterface(InterfaceConfig{ Name: "AnotherInterface", - ResolveType: func(value interface{}, info types.ResolveInfo) *types.Object { + ResolveType: func(value interface{}, info ResolveInfo) *Object { return nil }, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.String, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: String, }, }, }) - anotherObject := types.NewObject(types.ObjectConfig{ + anotherObject := NewObject(ObjectConfig{ Name: "AnotherObject", - Interfaces: []*types.Interface{anotherInterface}, - Fields: types.FieldConfigMap{ - "field": &types.FieldConfig{ - Type: types.NewNonNull(types.String), + Interfaces: []*Interface{anotherInterface}, + Fields: FieldConfigMap{ + "field": &FieldConfig{ + Type: NewNonNull(String), }, }, }) diff --git a/validator.go b/validator.go new file mode 100644 index 00000000..cedcd934 --- /dev/null +++ b/validator.go @@ -0,0 +1,11 @@ +package graphql + +type ValidationResult struct { + IsValid bool + Errors []FormattedError +} + +func ValidateDocument(schema Schema, ast *AstDocument) (vr ValidationResult) { + vr.IsValid = true + return vr +} diff --git a/validator/validator.go b/validator/validator.go deleted file mode 100644 index b9913452..00000000 --- a/validator/validator.go +++ /dev/null @@ -1,17 +0,0 @@ -package validator - -import ( - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/types" -) - -type ValidationResult struct { - IsValid bool - Errors []graphqlerrors.FormattedError -} - -func ValidateDocument(schema types.Schema, ast *ast.Document) (vr ValidationResult) { - vr.IsValid = true - return vr -} diff --git a/executor/values.go b/values.go similarity index 74% rename from executor/values.go rename to values.go index 21bed3df..0080bb05 100644 --- a/executor/values.go +++ b/values.go @@ -1,21 +1,18 @@ -package executor +package graphql import ( "encoding/json" "fmt" - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/kinds" - "github.com/chris-ramon/graphql/language/printer" - "github.com/chris-ramon/graphql/types" "math" "reflect" + + "github.com/chris-ramon/graphql/kinds" ) // Prepares an object map of variableValues of the correct type based on the // provided variable definitions and arbitrary input. If the input cannot be -// parsed to match the variable definitions, a Error will be returned. -func getVariableValues(schema types.Schema, definitionASTs []*ast.VariableDefinition, inputs map[string]interface{}) (map[string]interface{}, error) { +// parsed to match the variable definitions, a GraphQLError will be returned. +func getVariableValues(schema Schema, definitionASTs []*AstVariableDefinition, inputs map[string]interface{}) (map[string]interface{}, error) { values := map[string]interface{}{} for _, defAST := range definitionASTs { if defAST == nil || defAST.Variable == nil || defAST.Variable.Name == nil { @@ -33,9 +30,9 @@ func getVariableValues(schema types.Schema, definitionASTs []*ast.VariableDefini // Prepares an object map of argument values given a list of argument // definitions and list of argument AST nodes. -func getArgumentValues(argDefs []*types.Argument, argASTs []*ast.Argument, variableVariables map[string]interface{}) (map[string]interface{}, error) { +func getArgumentValues(argDefs []*Argument, argASTs []*AstArgument, variableVariables map[string]interface{}) (map[string]interface{}, error) { - argASTMap := map[string]*ast.Argument{} + argASTMap := map[string]*AstArgument{} for _, argAST := range argASTs { if argAST.Name != nil { argASTMap[argAST.Name.Value] = argAST @@ -45,7 +42,7 @@ func getArgumentValues(argDefs []*types.Argument, argASTs []*ast.Argument, varia for _, argDef := range argDefs { name := argDef.Name - var valueAST ast.Value + var valueAST Value if argAST, ok := argASTMap[name]; ok { valueAST = argAST.Value } @@ -62,18 +59,18 @@ func getArgumentValues(argDefs []*types.Argument, argASTs []*ast.Argument, varia // Given a variable definition, and any value of input, return a value which // adheres to the variable definition, or throw an error. -func getVariableValue(schema types.Schema, definitionAST *ast.VariableDefinition, input interface{}) (interface{}, error) { +func getVariableValue(schema Schema, definitionAST *AstVariableDefinition, input interface{}) (interface{}, error) { ttype, err := typeFromAST(schema, definitionAST.Type) if err != nil { return nil, err } variable := definitionAST.Variable - if ttype == nil || !types.IsInputType(ttype) { - return "", graphqlerrors.NewError( + if ttype == nil || !IsInputType(ttype) { + return "", NewError( fmt.Sprintf(`Variable "$%v" expected value of type `+ - `"%v" which cannot be used as an input type.`, variable.Name.Value, printer.Print(definitionAST.Type)), - []ast.Node{definitionAST}, + `"%v" which cannot be used as an input type.`, variable.Name.Value, Print(definitionAST.Type)), + []Node{definitionAST}, "", nil, []int{}, @@ -92,10 +89,10 @@ func getVariableValue(schema types.Schema, definitionAST *ast.VariableDefinition return coerceValue(ttype, input), nil } if isNullish(input) { - return "", graphqlerrors.NewError( + return "", NewError( fmt.Sprintf(`Variable "$%v" of required type `+ - `"%v" was not provided.`, variable.Name.Value, printer.Print(definitionAST.Type)), - []ast.Node{definitionAST}, + `"%v" was not provided.`, variable.Name.Value, Print(definitionAST.Type)), + []Node{definitionAST}, "", nil, []int{}, @@ -106,10 +103,10 @@ func getVariableValue(schema types.Schema, definitionAST *ast.VariableDefinition if err == nil { inputStr = string(b) } - return "", graphqlerrors.NewError( + return "", NewError( fmt.Sprintf(`Variable "$%v" expected value of type `+ - `"%v" but got: %v.`, variable.Name.Value, printer.Print(definitionAST.Type), inputStr), - []ast.Node{definitionAST}, + `"%v" but got: %v.`, variable.Name.Value, Print(definitionAST.Type), inputStr), + []Node{definitionAST}, "", nil, []int{}, @@ -117,14 +114,14 @@ func getVariableValue(schema types.Schema, definitionAST *ast.VariableDefinition } // Given a type and any value, return a runtime value coerced to match the type. -func coerceValue(ttype types.Input, value interface{}) interface{} { - if ttype, ok := ttype.(*types.NonNull); ok { +func coerceValue(ttype Input, value interface{}) interface{} { + if ttype, ok := ttype.(*NonNull); ok { return coerceValue(ttype.OfType, value) } if isNullish(value) { return nil } - if ttype, ok := ttype.(*types.List); ok { + if ttype, ok := ttype.(*List); ok { itemType := ttype.OfType valType := reflect.ValueOf(value) if valType.Kind() == reflect.Slice { @@ -139,7 +136,7 @@ func coerceValue(ttype types.Input, value interface{}) interface{} { val := coerceValue(itemType, value) return []interface{}{val} } - if ttype, ok := ttype.(*types.InputObject); ok { + if ttype, ok := ttype.(*InputObject); ok { valueMap, ok := value.(map[string]interface{}) if !ok { @@ -161,12 +158,12 @@ func coerceValue(ttype types.Input, value interface{}) interface{} { } switch ttype := ttype.(type) { - case *types.Scalar: + case *Scalar: parsed := ttype.ParseValue(value) if !isNullish(parsed) { return parsed } - case *types.Enum: + case *Enum: parsed := ttype.ParseValue(value) if !isNullish(parsed) { return parsed @@ -178,21 +175,21 @@ func coerceValue(ttype types.Input, value interface{}) interface{} { // graphql-js/src/utilities.js` // TODO: figure out where to organize utils -func typeFromAST(schema types.Schema, inputTypeAST ast.Type) (types.Type, error) { +func typeFromAST(schema Schema, inputTypeAST AstType) (Type, error) { switch inputTypeAST := inputTypeAST.(type) { - case *ast.ListType: + case *AstList: innerType, err := typeFromAST(schema, inputTypeAST.Type) if err != nil { return nil, err } - return types.NewList(innerType), nil - case *ast.NonNullType: + return NewList(innerType), nil + case *AstNonNull: innerType, err := typeFromAST(schema, inputTypeAST.Type) if err != nil { return nil, err } - return types.NewNonNull(innerType), nil - case *ast.NamedType: + return NewNonNull(innerType), nil + case *AstNamed: nameValue := "" if inputTypeAST.Name != nil { nameValue = inputTypeAST.Name.Value @@ -200,7 +197,7 @@ func typeFromAST(schema types.Schema, inputTypeAST ast.Type) (types.Type, error) ttype := schema.GetType(nameValue) return ttype, nil default: - return nil, invariant(inputTypeAST.GetKind() == kinds.NamedType, "Must be a named type.") + return nil, invariant(inputTypeAST.GetKind() == kinds.Named, "Must be a named type.") } } @@ -208,8 +205,8 @@ func typeFromAST(schema types.Schema, inputTypeAST ast.Type) (types.Type, error) // Given a value and a GraphQL type, determine if the value will be // accepted for that type. This is primarily useful for validating the // runtime values of query variables. -func isValidInputValue(value interface{}, ttype types.Input) bool { - if ttype, ok := ttype.(*types.NonNull); ok { +func isValidInputValue(value interface{}, ttype Input) bool { + if ttype, ok := ttype.(*NonNull); ok { if isNullish(value) { return false } @@ -221,7 +218,7 @@ func isValidInputValue(value interface{}, ttype types.Input) bool { } switch ttype := ttype.(type) { - case *types.List: + case *List: itemType := ttype.OfType valType := reflect.ValueOf(value) if valType.Kind() == reflect.Ptr { @@ -238,7 +235,7 @@ func isValidInputValue(value interface{}, ttype types.Input) bool { } return isValidInputValue(value, itemType) - case *types.InputObject: + case *InputObject: valueMap, ok := value.(map[string]interface{}) if !ok { return false @@ -262,10 +259,10 @@ func isValidInputValue(value interface{}, ttype types.Input) bool { } switch ttype := ttype.(type) { - case *types.Scalar: + case *Scalar: parsedVal := ttype.ParseValue(value) return !isNullish(parsedVal) - case *types.Enum: + case *Enum: parsedVal := ttype.ParseValue(value) return !isNullish(parsedVal) } @@ -304,9 +301,9 @@ func isNullish(value interface{}) bool { * | Int / Float | Number | * */ -func valueFromAST(valueAST ast.Value, ttype types.Input, variables map[string]interface{}) interface{} { +func valueFromAST(valueAST Value, ttype Input, variables map[string]interface{}) interface{} { - if ttype, ok := ttype.(*types.NonNull); ok { + if ttype, ok := ttype.(*NonNull); ok { val := valueFromAST(valueAST, ttype.OfType, variables) return val } @@ -315,7 +312,7 @@ func valueFromAST(valueAST ast.Value, ttype types.Input, variables map[string]in return nil } - if valueAST, ok := valueAST.(*ast.Variable); ok && valueAST.Kind == kinds.Variable { + if valueAST, ok := valueAST.(*AstVariable); ok && valueAST.Kind == kinds.Variable { if valueAST.Name == nil { return nil } @@ -333,9 +330,9 @@ func valueFromAST(valueAST ast.Value, ttype types.Input, variables map[string]in return variableVal } - if ttype, ok := ttype.(*types.List); ok { + if ttype, ok := ttype.(*List); ok { itemType := ttype.OfType - if valueAST, ok := valueAST.(*ast.ListValue); ok && valueAST.Kind == kinds.ListValue { + if valueAST, ok := valueAST.(*AstListValue); ok && valueAST.Kind == kinds.ListValue { values := []interface{}{} for _, itemAST := range valueAST.Values { v := valueFromAST(itemAST, itemType, variables) @@ -347,12 +344,12 @@ func valueFromAST(valueAST ast.Value, ttype types.Input, variables map[string]in return []interface{}{v} } - if ttype, ok := ttype.(*types.InputObject); ok { - valueAST, ok := valueAST.(*ast.ObjectValue) + if ttype, ok := ttype.(*InputObject); ok { + valueAST, ok := valueAST.(*AstObjectValue) if !ok { return nil } - fieldASTs := map[string]*ast.ObjectField{} + fieldASTs := map[string]*AstObjectField{} for _, fieldAST := range valueAST.Fields { if fieldAST.Name == nil { continue @@ -379,12 +376,12 @@ func valueFromAST(valueAST ast.Value, ttype types.Input, variables map[string]in } switch ttype := ttype.(type) { - case *types.Scalar: + case *Scalar: parsed := ttype.ParseLiteral(valueAST) if !isNullish(parsed) { return parsed } - case *types.Enum: + case *Enum: parsed := ttype.ParseLiteral(valueAST) if !isNullish(parsed) { return parsed @@ -395,7 +392,7 @@ func valueFromAST(valueAST ast.Value, ttype types.Input, variables map[string]in func invariant(condition bool, message string) error { if !condition { - return graphqlerrors.NewFormattedError(message) + return NewFormattedError(message) } return nil } diff --git a/executor/variables_test.go b/variables_test.go similarity index 63% rename from executor/variables_test.go rename to variables_test.go index 830ab6c7..e9003531 100644 --- a/executor/variables_test.go +++ b/variables_test.go @@ -1,18 +1,12 @@ -package executor_test +package graphql import ( "encoding/json" - "github.com/chris-ramon/graphql/errors" - "github.com/chris-ramon/graphql/executor" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/testutil" - "github.com/chris-ramon/graphql/types" "reflect" "testing" ) -var testComplexScalar *types.Scalar = types.NewScalar(types.ScalarConfig{ +var testComplexScalar *Scalar = NewScalar(ScalarConfig{ Name: "ComplexScalar", Serialize: func(value interface{}) interface{} { if value == "DeserializedValue" { @@ -26,7 +20,7 @@ var testComplexScalar *types.Scalar = types.NewScalar(types.ScalarConfig{ } return nil }, - ParseLiteral: func(valueAST ast.Value) interface{} { + ParseLiteral: func(valueAST Value) interface{} { astValue := valueAST.GetValue() if astValue, ok := astValue.(string); ok && astValue == "SerializedValue" { return "DeserializedValue" @@ -35,25 +29,25 @@ var testComplexScalar *types.Scalar = types.NewScalar(types.ScalarConfig{ }, }) -var testInputObject *types.InputObject = types.NewInputObject(types.InputObjectConfig{ +var testInputObject *InputObject = NewInputObject(InputObjectConfig{ Name: "TestInputObject", - Fields: types.InputObjectConfigFieldMap{ - "a": &types.InputObjectFieldConfig{ - Type: types.String, + Fields: InputObjectConfigFieldMap{ + "a": &InputObjectFieldConfig{ + Type: String, }, - "b": &types.InputObjectFieldConfig{ - Type: types.NewList(types.String), + "b": &InputObjectFieldConfig{ + Type: NewList(String), }, - "c": &types.InputObjectFieldConfig{ - Type: types.NewNonNull(types.String), + "c": &InputObjectFieldConfig{ + Type: NewNonNull(String), }, - "d": &types.InputObjectFieldConfig{ + "d": &InputObjectFieldConfig{ Type: testComplexScalar, }, }, }) -func inputResolved(p types.GQLFRParams) interface{} { +func inputResolved(p GQLFRParams) interface{} { input, ok := p.Args["input"] if !ok { return nil @@ -65,78 +59,78 @@ func inputResolved(p types.GQLFRParams) interface{} { return string(b) } -var testType *types.Object = types.NewObject(types.ObjectConfig{ +var testType *Object = NewObject(ObjectConfig{ Name: "TestType", - Fields: types.FieldConfigMap{ - "fieldWithObjectInput": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ + Fields: FieldConfigMap{ + "fieldWithObjectInput": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ Type: testInputObject, }, }, Resolve: inputResolved, }, - "fieldWithNullableStringInput": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + "fieldWithNullableStringInput": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, }, }, Resolve: inputResolved, }, - "fieldWithNonNullableStringInput": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.NewNonNull(types.String), + "fieldWithNonNullableStringInput": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: NewNonNull(String), }, }, Resolve: inputResolved, }, - "fieldWithDefaultArgumentValue": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.String, + "fieldWithDefaultArgumentValue": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: String, DefaultValue: "Hello World", }, }, Resolve: inputResolved, }, - "list": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.NewList(types.String), + "list": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: NewList(String), }, }, Resolve: inputResolved, }, - "nnList": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.NewNonNull(types.NewList(types.String)), + "nnList": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: NewNonNull(NewList(String)), }, }, Resolve: inputResolved, }, - "listNN": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.NewList(types.NewNonNull(types.String)), + "listNN": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: NewList(NewNonNull(String)), }, }, Resolve: inputResolved, }, - "nnListNN": &types.FieldConfig{ - Type: types.String, - Args: types.FieldConfigArgument{ - "input": &types.ArgumentConfig{ - Type: types.NewNonNull(types.NewList(types.NewNonNull(types.String))), + "nnListNN": &FieldConfig{ + Type: String, + Args: FieldConfigArgument{ + "input": &ArgumentConfig{ + Type: NewNonNull(NewList(NewNonNull(String))), }, }, Resolve: inputResolved, @@ -144,7 +138,7 @@ var testType *types.Object = types.NewObject(types.ObjectConfig{ }, }) -var variablesTestSchema, _ = types.NewSchema(types.SchemaConfig{ +var variablesTestSchema, _ = NewSchema(SchemaConfig{ Query: testType, }) @@ -154,25 +148,25 @@ func TestVariables_ObjectsAndNullability_UsingInlineStructs_ExecutesWithComplexI fieldWithObjectInput(input: {a: "foo", b: ["bar"], c: "baz"}) } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ObjectsAndNullability_UsingInlineStructs_ProperlyParsesSingleValueToList(t *testing.T) { @@ -181,25 +175,25 @@ func TestVariables_ObjectsAndNullability_UsingInlineStructs_ProperlyParsesSingle fieldWithObjectInput(input: {a: "foo", b: "bar", c: "baz"}) } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ObjectsAndNullability_UsingInlineStructs_DoesNotUseIncorrectValue(t *testing.T) { @@ -208,35 +202,35 @@ func TestVariables_ObjectsAndNullability_UsingInlineStructs_DoesNotUseIncorrectV fieldWithObjectInput(input: ["foo", "bar", "baz"]) } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithObjectInput": nil, }, } // parse query - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } -func testVariables_ObjectsAndNullability_UsingVariables_GetAST(t *testing.T) *ast.Document { +func testVariables_ObjectsAndNullability_UsingVariables_GetAST(t *testing.T) *AstDocument { doc := ` query q($input: TestInputObject) { fieldWithObjectInput(input: $input) } ` - return testutil.Parse(t, doc) + return TestParse(t, doc) } func TestVariables_ObjectsAndNullability_UsingVariables_ExecutesWithComplexInput(t *testing.T) { @@ -247,7 +241,7 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ExecutesWithComplexInput "c": "baz", }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, @@ -256,17 +250,17 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ExecutesWithComplexInput ast := testVariables_ObjectsAndNullability_UsingVariables_GetAST(t) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -277,25 +271,25 @@ func TestVariables_ObjectsAndNullability_UsingVariables_UsesDefaultValueWhenNotP fieldWithObjectInput(input: $input) } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, } - withDefaultsAST := testutil.Parse(t, doc) + withDefaultsAST := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: withDefaultsAST, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ObjectsAndNullability_UsingVariables_ProperlyParsesSingleValueToList(t *testing.T) { @@ -306,7 +300,7 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ProperlyParsesSingleValu "c": "baz", }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"a":"foo","b":["bar"],"c":"baz"}`, }, @@ -315,17 +309,17 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ProperlyParsesSingleValu ast := testVariables_ObjectsAndNullability_UsingVariables_GetAST(t) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ObjectsAndNullability_UsingVariables_ExecutesWithComplexScalarInput(t *testing.T) { @@ -335,7 +329,7 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ExecutesWithComplexScala "d": "SerializedValue", }, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithObjectInput": `{"c":"foo","d":"DeserializedValue"}`, }, @@ -344,17 +338,17 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ExecutesWithComplexScala ast := testVariables_ObjectsAndNullability_UsingVariables_GetAST(t) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnNullForNestedNonNull(t *testing.T) { @@ -365,14 +359,14 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnNullForNestedNon "c": nil, }, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: {"a":"foo","b":"bar","c":null}.`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, @@ -383,31 +377,31 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnNullForNestedNon ast := testVariables_ObjectsAndNullability_UsingVariables_GetAST(t) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnIncorrectType(t *testing.T) { params := map[string]interface{}{ "input": "foo bar", } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: "foo bar".`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, @@ -418,17 +412,17 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnIncorrectType(t ast := testVariables_ObjectsAndNullability_UsingVariables_GetAST(t) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnOmissionOfNestedNonNull(t *testing.T) { @@ -438,14 +432,14 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnOmissionOfNested "b": "bar", }, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: {"a":"foo","b":"bar"}.`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, @@ -456,17 +450,17 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnOmissionOfNested ast := testVariables_ObjectsAndNullability_UsingVariables_GetAST(t) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnAdditionOfUnknownInputField(t *testing.T) { @@ -478,14 +472,14 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnAdditionOfUnknow "d": "dog", }, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: {"a":"foo","b":"bar","c":"baz","d":"dog"}.`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, @@ -496,17 +490,17 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnAdditionOfUnknow ast := testVariables_ObjectsAndNullability_UsingVariables_GetAST(t) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -516,25 +510,25 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeOmitted(t *testing.T) fieldWithNullableStringInput } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": nil, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_NullableScalars_AllowsNullableInputsToBeOmittedInAVariable(t *testing.T) { @@ -543,25 +537,25 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeOmittedInAVariable(t fieldWithNullableStringInput(input: $value) } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": nil, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_NullableScalars_AllowsNullableInputsToBeOmittedInAnUnlistedVariable(t *testing.T) { @@ -570,25 +564,25 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeOmittedInAnUnlistedVa fieldWithNullableStringInput(input: $value) } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": nil, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_NullableScalars_AllowsNullableInputsToBeSetToNullInAVariable(t *testing.T) { @@ -600,26 +594,26 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeSetToNullInAVariable( params := map[string]interface{}{ "value": nil, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": nil, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_NullableScalars_AllowsNullableInputsToBeSetToAValueInAVariable(t *testing.T) { @@ -631,26 +625,26 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeSetToAValueInAVariabl params := map[string]interface{}{ "value": "a", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": `"a"`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_NullableScalars_AllowsNullableInputsToBeSetToAValueDirectly(t *testing.T) { @@ -659,25 +653,25 @@ func TestVariables_NullableScalars_AllowsNullableInputsToBeSetToAValueDirectly(t fieldWithNullableStringInput(input: "a") } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithNullableStringInput": `"a"`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -689,13 +683,13 @@ func TestVariables_NonNullableScalars_DoesNotAllowNonNullableInputsToBeOmittedIn } ` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$value" of required type "String!" was not provided.`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 31, }, }, @@ -703,19 +697,19 @@ func TestVariables_NonNullableScalars_DoesNotAllowNonNullableInputsToBeOmittedIn }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_NonNullableScalars_DoesNotAllowNonNullableInputsToBeSetToNullInAVariable(t *testing.T) { @@ -728,13 +722,13 @@ func TestVariables_NonNullableScalars_DoesNotAllowNonNullableInputsToBeSetToNull params := map[string]interface{}{ "value": nil, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$value" of required type "String!" was not provided.`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 31, }, }, @@ -742,20 +736,20 @@ func TestVariables_NonNullableScalars_DoesNotAllowNonNullableInputsToBeSetToNull }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_NonNullableScalars_AllowsNonNullableInputsToBeSetToAValueInAVariable(t *testing.T) { @@ -768,26 +762,26 @@ func TestVariables_NonNullableScalars_AllowsNonNullableInputsToBeSetToAValueInAV params := map[string]interface{}{ "value": "a", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithNonNullableStringInput": `"a"`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_NonNullableScalars_AllowsNonNullableInputsToBeSetToAValueDirectly(t *testing.T) { @@ -801,26 +795,26 @@ func TestVariables_NonNullableScalars_AllowsNonNullableInputsToBeSetToAValueDire "value": "a", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithNonNullableStringInput": `"a"`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_NonNullableScalars_PassesAlongNullForNonNullableInputsIfExplicitlySetInTheQuery(t *testing.T) { @@ -834,26 +828,26 @@ func TestVariables_NonNullableScalars_PassesAlongNullForNonNullableInputsIfExpli "value": "a", } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithNonNullableStringInput": nil, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -867,25 +861,25 @@ func TestVariables_ListsAndNullability_AllowsListsToBeNull(t *testing.T) { "input": nil, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "list": nil, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_AllowsListsToContainValues(t *testing.T) { @@ -898,25 +892,25 @@ func TestVariables_ListsAndNullability_AllowsListsToContainValues(t *testing.T) "input": []interface{}{"A"}, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "list": `["A"]`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_AllowsListsToContainNull(t *testing.T) { @@ -929,25 +923,25 @@ func TestVariables_ListsAndNullability_AllowsListsToContainNull(t *testing.T) { "input": []interface{}{"A", nil, "B"}, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "list": `["A",null,"B"]`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_DoesNotAllowNonNullListsToBeNull(t *testing.T) { @@ -956,32 +950,32 @@ func TestVariables_ListsAndNullability_DoesNotAllowNonNullListsToBeNull(t *testi nnList(input: $input) } ` - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" of required type "[String]!" was not provided.`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, }, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_AllowsNonNullListsToContainValues(t *testing.T) { @@ -993,25 +987,25 @@ func TestVariables_ListsAndNullability_AllowsNonNullListsToContainValues(t *test params := map[string]interface{}{ "input": []interface{}{"A"}, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nnList": `["A"]`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_AllowsNonNullListsToContainNull(t *testing.T) { @@ -1023,25 +1017,25 @@ func TestVariables_ListsAndNullability_AllowsNonNullListsToContainNull(t *testin params := map[string]interface{}{ "input": []interface{}{"A", nil, "B"}, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nnList": `["A",null,"B"]`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_AllowsListsOfNonNullsToBeNull(t *testing.T) { @@ -1053,25 +1047,25 @@ func TestVariables_ListsAndNullability_AllowsListsOfNonNullsToBeNull(t *testing. params := map[string]interface{}{ "input": nil, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "listNN": nil, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_AllowsListsOfNonNullsToContainValues(t *testing.T) { @@ -1083,25 +1077,25 @@ func TestVariables_ListsAndNullability_AllowsListsOfNonNullsToContainValues(t *t params := map[string]interface{}{ "input": []interface{}{"A"}, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "listNN": `["A"]`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) > 0 { t.Fatalf("wrong result, unexpected errors: %v", result.Errors) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_DoesNotAllowListOfNonNullsToContainNull(t *testing.T) { @@ -1113,34 +1107,34 @@ func TestVariables_ListsAndNullability_DoesNotAllowListOfNonNullsToContainNull(t params := map[string]interface{}{ "input": []interface{}{"A", nil, "B"}, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" expected value of type "[String!]" but got: ` + `["A",null,"B"].`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, }, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_DoesNotAllowNonNullListOfNonNullsToBeNull(t *testing.T) { @@ -1152,33 +1146,33 @@ func TestVariables_ListsAndNullability_DoesNotAllowNonNullListOfNonNullsToBeNull params := map[string]interface{}{ "input": nil, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" of required type "[String!]!" was not provided.`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, }, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_AllowsNonNullListsOfNonNulsToContainValues(t *testing.T) { @@ -1190,25 +1184,25 @@ func TestVariables_ListsAndNullability_AllowsNonNullListsOfNonNulsToContainValue params := map[string]interface{}{ "input": []interface{}{"A"}, } - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "nnListNN": `["A"]`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_DoesNotAllowNonNullListOfNonNullsToContainNull(t *testing.T) { @@ -1220,34 +1214,34 @@ func TestVariables_ListsAndNullability_DoesNotAllowNonNullListOfNonNullsToContai params := map[string]interface{}{ "input": []interface{}{"A", nil, "B"}, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" expected value of type "[String!]!" but got: ` + `["A",null,"B"].`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, }, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_DoesNotAllowInvalidTypesToBeUsedAsValues(t *testing.T) { @@ -1261,33 +1255,33 @@ func TestVariables_ListsAndNullability_DoesNotAllowInvalidTypesToBeUsedAsValues( "list": []interface{}{"A", "B"}, }, } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" expected value of type "TestType!" which cannot be used as an input type.`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, }, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_ListsAndNullability_DoesNotAllowUnknownTypesToBeUsedAsValues(t *testing.T) { @@ -1299,33 +1293,33 @@ func TestVariables_ListsAndNullability_DoesNotAllowUnknownTypesToBeUsedAsValues( params := map[string]interface{}{ "input": "whoknows", } - expected := &types.Result{ + expected := &Result{ Data: nil, - Errors: []graphqlerrors.FormattedError{ - graphqlerrors.FormattedError{ + Errors: []FormattedError{ + FormattedError{ Message: `Variable "$input" expected value of type "UnknownType!" which cannot be used as an input type.`, - Locations: []location.SourceLocation{ - location.SourceLocation{ + Locations: []SourceLocation{ + SourceLocation{ Line: 2, Column: 17, }, }, }, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, Args: params, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } @@ -1335,24 +1329,24 @@ func TestVariables_UsesArgumentDefaultValues_WhenNoArgumentProvided(t *testing.T fieldWithDefaultArgumentValue } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithDefaultArgumentValue": `"Hello World"`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_UsesArgumentDefaultValues_WhenNullableVariableProvided(t *testing.T) { @@ -1361,24 +1355,24 @@ func TestVariables_UsesArgumentDefaultValues_WhenNullableVariableProvided(t *tes fieldWithDefaultArgumentValue(input: $optional) } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithDefaultArgumentValue": `"Hello World"`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } func TestVariables_UsesArgumentDefaultValues_WhenArgumentProvidedCannotBeParsed(t *testing.T) { @@ -1387,23 +1381,23 @@ func TestVariables_UsesArgumentDefaultValues_WhenArgumentProvidedCannotBeParsed( fieldWithDefaultArgumentValue(input: WRONG_TYPE) } ` - expected := &types.Result{ + expected := &Result{ Data: map[string]interface{}{ "fieldWithDefaultArgumentValue": `"Hello World"`, }, } - ast := testutil.Parse(t, doc) + ast := TestParse(t, doc) // execute - ep := executor.ExecuteParams{ + ep := ExecuteParams{ Schema: variablesTestSchema, AST: ast, } - result := testutil.Execute(t, ep) + result := TestExecute(t, ep) if len(result.Errors) != len(expected.Errors) { - t.Fatalf("Unexpected errors, Diff: %v", testutil.Diff(expected.Errors, result.Errors)) + t.Fatalf("Unexpected errors, Diff: %v", Diff(expected.Errors, result.Errors)) } if !reflect.DeepEqual(expected, result) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expected, result)) } } diff --git a/language/visitor/visitor.go b/visitor.go similarity index 98% rename from language/visitor/visitor.go rename to visitor.go index 8cb8107b..ceada812 100644 --- a/language/visitor/visitor.go +++ b/visitor.go @@ -1,4 +1,4 @@ -package visitor +package graphql import ( "encoding/json" @@ -77,9 +77,9 @@ var QueryDocumentKeys KeyMap = KeyMap{ "Arguments", }, - "NamedType": []string{"Name"}, - "ListType": []string{"Type"}, - "NonNullType": []string{"Type"}, + "Named": []string{"Name"}, + "List": []string{"Type"}, + "NonNull": []string{"Type"}, "ObjectDefinition": []string{ "Name", diff --git a/language/visitor/visitor_test.go b/visitor_test.go similarity index 73% rename from language/visitor/visitor_test.go rename to visitor_test.go index ad9c6d60..2959e78b 100644 --- a/language/visitor/visitor_test.go +++ b/visitor_test.go @@ -1,20 +1,16 @@ -package visitor_test +package graphql import ( - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/parser" - "github.com/chris-ramon/graphql/language/visitor" - "github.com/chris-ramon/graphql/testutil" "io/ioutil" "reflect" "strings" "testing" ) -func parse(t *testing.T, query string) *ast.Document { - astDoc, err := parser.Parse(parser.ParseParams{ +func parseeee(t *testing.T, query string) *AstDocument { + astDoc, err := Parse(ParseParams{ Source: query, - Options: parser.ParseOptions{ + Options: ParseOptions{ NoLocation: true, }, }) @@ -26,7 +22,7 @@ func parse(t *testing.T, query string) *ast.Document { // Helper functions to get map value by key // Allow keys to specify dot paths (e.g `Name.Value`) -func getMapValue(m map[string]interface{}, key string) interface{} { +func testGetMapValue(m map[string]interface{}, key string) interface{} { tokens := strings.Split(key, ".") valMap := m for _, token := range tokens { @@ -46,7 +42,7 @@ func getMapValue(m map[string]interface{}, key string) interface{} { } return valMap } -func getMapValueString(m map[string]interface{}, key string) string { +func testGetMapValueString(m map[string]interface{}, key string) string { tokens := strings.Split(key, ".") valMap := m for _, token := range tokens { @@ -67,57 +63,57 @@ func getMapValueString(m map[string]interface{}, key string) string { func TestVisitor_AllowsForEditingOnEnter(t *testing.T) { query := `{ a, b, c { a, b, c } }` - astDoc := parse(t, query) + astDoc := parseeee(t, query) expectedQuery := `{ a, c { a, c } }` - expectedAST := parse(t, expectedQuery) - v := &visitor.VisitorOptions{ - Enter: func(p visitor.VisitFuncParams) (string, interface{}) { + expectedAST := parseeee(t, expectedQuery) + v := &VisitorOptions{ + Enter: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - if getMapValueString(node, "Kind") == "Field" && getMapValueString(node, "Name.Value") == "b" { - return visitor.ActionUpdate, nil + if testGetMapValueString(node, "Kind") == "Field" && testGetMapValueString(node, "Name.Value") == "b" { + return ActionUpdate, nil } } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, } - editedAst := visitor.Visit(astDoc, v, nil) - if !reflect.DeepEqual(testutil.ASTToJSON(t, expectedAST), editedAst) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedAST, editedAst)) + editedAst := Visit(astDoc, v, nil) + if !reflect.DeepEqual(ASTToJSON(t, expectedAST), editedAst) { + t.Fatalf("Unexpected result, Diff: %v", Diff(expectedAST, editedAst)) } } func TestVisitor_AllowsForEditingOnLeave(t *testing.T) { query := `{ a, b, c { a, b, c } }` - astDoc := parse(t, query) + astDoc := parseeee(t, query) expectedQuery := `{ a, c { a, c } }` - expectedAST := parse(t, expectedQuery) - v := &visitor.VisitorOptions{ - Leave: func(p visitor.VisitFuncParams) (string, interface{}) { + expectedAST := parseeee(t, expectedQuery) + v := &VisitorOptions{ + Leave: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - if getMapValueString(node, "Kind") == "Field" && getMapValueString(node, "Name.Value") == "b" { - return visitor.ActionUpdate, nil + if testGetMapValueString(node, "Kind") == "Field" && testGetMapValueString(node, "Name.Value") == "b" { + return ActionUpdate, nil } } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, } - editedAst := visitor.Visit(astDoc, v, nil) - if !reflect.DeepEqual(testutil.ASTToJSON(t, expectedAST), editedAst) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedAST, editedAst)) + editedAst := Visit(astDoc, v, nil) + if !reflect.DeepEqual(ASTToJSON(t, expectedAST), editedAst) { + t.Fatalf("Unexpected result, Diff: %v", Diff(expectedAST, editedAst)) } } func TestVisitor_VisitsEditedNode(t *testing.T) { query := `{ a { x } }` - astDoc := parse(t, query) + astDoc := parseeee(t, query) addedField := map[string]interface{}{ "Kind": "Field", @@ -128,14 +124,14 @@ func TestVisitor_VisitsEditedNode(t *testing.T) { } didVisitAddedField := false - v := &visitor.VisitorOptions{ - Enter: func(p visitor.VisitFuncParams) (string, interface{}) { + v := &VisitorOptions{ + Enter: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - if getMapValueString(node, "Kind") == "Field" && getMapValueString(node, "Name.Value") == "a" { - s := getMapValue(node, "SelectionSet.Selections").([]interface{}) + if testGetMapValueString(node, "Kind") == "Field" && testGetMapValueString(node, "Name.Value") == "a" { + s := testGetMapValue(node, "SelectionSet.Selections").([]interface{}) s = append(s, addedField) - return visitor.ActionUpdate, map[string]interface{}{ + return ActionUpdate, map[string]interface{}{ "Kind": "Field", "SelectionSet": s, } @@ -144,11 +140,11 @@ func TestVisitor_VisitsEditedNode(t *testing.T) { didVisitAddedField = true } } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, } - _ = visitor.Visit(astDoc, v, nil) + _ = Visit(astDoc, v, nil) if didVisitAddedField == false { t.Fatalf("Unexpected result, expected didVisitAddedField == true") } @@ -156,7 +152,7 @@ func TestVisitor_VisitsEditedNode(t *testing.T) { func TestVisitor_AllowsSkippingASubTree(t *testing.T) { query := `{ a, b { x }, c }` - astDoc := parse(t, query) + astDoc := parseeee(t, query) visited := []interface{}{} expectedVisited := []interface{}{ @@ -177,37 +173,37 @@ func TestVisitor_AllowsSkippingASubTree(t *testing.T) { []interface{}{"leave", "Document", nil}, } - v := &visitor.VisitorOptions{ - Enter: func(p visitor.VisitFuncParams) (string, interface{}) { + v := &VisitorOptions{ + Enter: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - visited = append(visited, []interface{}{"enter", getMapValue(node, "Kind"), getMapValue(node, "Value")}) - if getMapValueString(node, "Kind") == "Field" && getMapValueString(node, "Name.Value") == "b" { - return visitor.ActionSkip, nil + visited = append(visited, []interface{}{"enter", testGetMapValue(node, "Kind"), testGetMapValue(node, "Value")}) + if testGetMapValueString(node, "Kind") == "Field" && testGetMapValueString(node, "Name.Value") == "b" { + return ActionSkip, nil } } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - Leave: func(p visitor.VisitFuncParams) (string, interface{}) { + Leave: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - visited = append(visited, []interface{}{"leave", getMapValue(node, "Kind"), getMapValue(node, "Value")}) + visited = append(visited, []interface{}{"leave", testGetMapValue(node, "Kind"), testGetMapValue(node, "Value")}) } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, } - _ = visitor.Visit(astDoc, v, nil) + _ = Visit(astDoc, v, nil) if !reflect.DeepEqual(visited, expectedVisited) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedVisited, visited)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expectedVisited, visited)) } } func TestVisitor_AllowsANamedFunctionsVisitorAPI(t *testing.T) { query := `{ a, b { x }, c }` - astDoc := parse(t, query) + astDoc := parseeee(t, query) visited := []interface{}{} expectedVisited := []interface{}{ @@ -221,50 +217,50 @@ func TestVisitor_AllowsANamedFunctionsVisitorAPI(t *testing.T) { []interface{}{"leave", "SelectionSet", nil}, } - v := &visitor.VisitorOptions{ - KindFuncMap: map[string]visitor.NamedVisitFuncs{ - "Name": visitor.NamedVisitFuncs{ - Kind: func(p visitor.VisitFuncParams) (string, interface{}) { + v := &VisitorOptions{ + KindFuncMap: map[string]NamedVisitFuncs{ + "Name": NamedVisitFuncs{ + Kind: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - visited = append(visited, []interface{}{"enter", getMapValue(node, "Kind"), getMapValue(node, "Value")}) + visited = append(visited, []interface{}{"enter", testGetMapValue(node, "Kind"), testGetMapValue(node, "Value")}) } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, }, - "SelectionSet": visitor.NamedVisitFuncs{ - Enter: func(p visitor.VisitFuncParams) (string, interface{}) { + "SelectionSet": NamedVisitFuncs{ + Enter: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - visited = append(visited, []interface{}{"enter", getMapValue(node, "Kind"), getMapValue(node, "Value")}) + visited = append(visited, []interface{}{"enter", testGetMapValue(node, "Kind"), testGetMapValue(node, "Value")}) } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - Leave: func(p visitor.VisitFuncParams) (string, interface{}) { + Leave: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - visited = append(visited, []interface{}{"leave", getMapValue(node, "Kind"), getMapValue(node, "Value")}) + visited = append(visited, []interface{}{"leave", testGetMapValue(node, "Kind"), testGetMapValue(node, "Value")}) } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, }, }, } - _ = visitor.Visit(astDoc, v, nil) + _ = Visit(astDoc, v, nil) if !reflect.DeepEqual(visited, expectedVisited) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedVisited, visited)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expectedVisited, visited)) } } func TestVisitor_VisitsKitchenSink(t *testing.T) { - b, err := ioutil.ReadFile("./../parser/kitchen-sink.graphql") + b, err := ioutil.ReadFile("./kitchen-sink.graphql") if err != nil { t.Fatalf("unable to load kitchen-sink.graphql") } query := string(b) - astDoc := parse(t, query) + astDoc := parseeee(t, query) visited := []interface{}{} expectedVisited := []interface{}{ @@ -277,20 +273,20 @@ func TestVisitor_VisitsKitchenSink(t *testing.T) { []interface{}{"enter", "Name", "Name", "Variable"}, []interface{}{"leave", "Name", "Name", "Variable"}, []interface{}{"leave", "Variable", "Variable", "VariableDefinition"}, - []interface{}{"enter", "NamedType", "Type", "VariableDefinition"}, - []interface{}{"enter", "Name", "Name", "NamedType"}, - []interface{}{"leave", "Name", "Name", "NamedType"}, - []interface{}{"leave", "NamedType", "Type", "VariableDefinition"}, + []interface{}{"enter", "Named", "Type", "VariableDefinition"}, + []interface{}{"enter", "Name", "Name", "Named"}, + []interface{}{"leave", "Name", "Name", "Named"}, + []interface{}{"leave", "Named", "Type", "VariableDefinition"}, []interface{}{"leave", "VariableDefinition", 0, nil}, []interface{}{"enter", "VariableDefinition", 1, nil}, []interface{}{"enter", "Variable", "Variable", "VariableDefinition"}, []interface{}{"enter", "Name", "Name", "Variable"}, []interface{}{"leave", "Name", "Name", "Variable"}, []interface{}{"leave", "Variable", "Variable", "VariableDefinition"}, - []interface{}{"enter", "NamedType", "Type", "VariableDefinition"}, - []interface{}{"enter", "Name", "Name", "NamedType"}, - []interface{}{"leave", "Name", "Name", "NamedType"}, - []interface{}{"leave", "NamedType", "Type", "VariableDefinition"}, + []interface{}{"enter", "Named", "Type", "VariableDefinition"}, + []interface{}{"enter", "Name", "Name", "Named"}, + []interface{}{"leave", "Name", "Name", "Named"}, + []interface{}{"leave", "Named", "Type", "VariableDefinition"}, []interface{}{"enter", "EnumValue", "DefaultValue", "VariableDefinition"}, []interface{}{"leave", "EnumValue", "DefaultValue", "VariableDefinition"}, []interface{}{"leave", "VariableDefinition", 1, nil}, @@ -316,10 +312,10 @@ func TestVisitor_VisitsKitchenSink(t *testing.T) { []interface{}{"leave", "Name", "Name", "Field"}, []interface{}{"leave", "Field", 0, nil}, []interface{}{"enter", "InlineFragment", 1, nil}, - []interface{}{"enter", "NamedType", "TypeCondition", "InlineFragment"}, - []interface{}{"enter", "Name", "Name", "NamedType"}, - []interface{}{"leave", "Name", "Name", "NamedType"}, - []interface{}{"leave", "NamedType", "TypeCondition", "InlineFragment"}, + []interface{}{"enter", "Named", "TypeCondition", "InlineFragment"}, + []interface{}{"enter", "Name", "Name", "Named"}, + []interface{}{"leave", "Name", "Name", "Named"}, + []interface{}{"leave", "Named", "TypeCondition", "InlineFragment"}, []interface{}{"enter", "Directive", 0, nil}, []interface{}{"enter", "Name", "Name", "Directive"}, []interface{}{"leave", "Name", "Name", "Directive"}, @@ -418,10 +414,10 @@ func TestVisitor_VisitsKitchenSink(t *testing.T) { []interface{}{"enter", "FragmentDefinition", 2, nil}, []interface{}{"enter", "Name", "Name", "FragmentDefinition"}, []interface{}{"leave", "Name", "Name", "FragmentDefinition"}, - []interface{}{"enter", "NamedType", "TypeCondition", "FragmentDefinition"}, - []interface{}{"enter", "Name", "Name", "NamedType"}, - []interface{}{"leave", "Name", "Name", "NamedType"}, - []interface{}{"leave", "NamedType", "TypeCondition", "FragmentDefinition"}, + []interface{}{"enter", "Named", "TypeCondition", "FragmentDefinition"}, + []interface{}{"enter", "Name", "Name", "Named"}, + []interface{}{"leave", "Name", "Name", "Named"}, + []interface{}{"leave", "Named", "TypeCondition", "FragmentDefinition"}, []interface{}{"enter", "SelectionSet", "SelectionSet", "FragmentDefinition"}, []interface{}{"enter", "Field", 0, nil}, []interface{}{"enter", "Name", "Name", "Field"}, @@ -484,8 +480,8 @@ func TestVisitor_VisitsKitchenSink(t *testing.T) { []interface{}{"leave", "Document", nil, nil}, } - v := &visitor.VisitorOptions{ - Enter: func(p visitor.VisitFuncParams) (string, interface{}) { + v := &VisitorOptions{ + Enter: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: @@ -494,11 +490,11 @@ func TestVisitor_VisitsKitchenSink(t *testing.T) { parent = map[string]interface{}{} } - visited = append(visited, []interface{}{"enter", getMapValue(node, "Kind"), p.Key, getMapValue(parent, "Kind")}) + visited = append(visited, []interface{}{"enter", testGetMapValue(node, "Kind"), p.Key, testGetMapValue(parent, "Kind")}) } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, - Leave: func(p visitor.VisitFuncParams) (string, interface{}) { + Leave: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: @@ -507,16 +503,16 @@ func TestVisitor_VisitsKitchenSink(t *testing.T) { parent = map[string]interface{}{} } - visited = append(visited, []interface{}{"leave", getMapValue(node, "Kind"), p.Key, getMapValue(parent, "Kind")}) + visited = append(visited, []interface{}{"leave", testGetMapValue(node, "Kind"), p.Key, testGetMapValue(parent, "Kind")}) } - return visitor.ActionNoChange, nil + return ActionNoChange, nil }, } - _ = visitor.Visit(astDoc, v, nil) + _ = Visit(astDoc, v, nil) if !reflect.DeepEqual(visited, expectedVisited) { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedVisited, visited)) + t.Fatalf("Unexpected result, Diff: %v", Diff(expectedVisited, visited)) } } @@ -526,7 +522,7 @@ func TestVisitor_ProducesHelpfulErrorMessages(t *testing.T) { err := r.(string) expectedErr := `Invalid AST Node (4): map[random:Data]` if err != expectedErr { - t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(err, expectedErr)) + t.Fatalf("Unexpected result, Diff: %v", Diff(err, expectedErr)) } return } @@ -535,5 +531,5 @@ func TestVisitor_ProducesHelpfulErrorMessages(t *testing.T) { astDoc := map[string]interface{}{ "random": "Data", } - _ = visitor.Visit(astDoc, nil, nil) + _ = Visit(astDoc, nil, nil) } From dd3a99aa4e2429a76dabfb31a07c6ea08a17de18 Mon Sep 17 00:00:00 2001 From: Nathaniel Maman Date: Fri, 30 Oct 2015 00:49:49 +0200 Subject: [PATCH 5/6] mv language related code to language dir --- abstract_test.go | 15 +- ast_arguments.go | 33 -- ast_definitions.go | 153 ------- ast_directives.go | 33 -- ast_document.go | 31 -- ast_location.go | 18 - ast_name.go | 31 -- ast_node.go | 45 -- ast_selections.go | 131 ------ ast_type_definitions.go | 402 ------------------ ast_types.go | 106 ----- ast_values.go | 305 ------------- definition.go | 16 +- enum_type_test.go | 26 +- executor.go | 124 +++--- executor_test.go | 29 +- error.go => gqlerrors/error.go | 18 +- formatted.go => gqlerrors/formatted.go | 8 +- gqlerrors/located.go | 31 ++ sortutil.go => gqlerrors/sortutil.go | 2 +- syntax.go => gqlerrors/syntax.go | 14 +- graphql.go | 9 +- introspection.go | 29 +- introspection_test.go | 11 +- language/ast/arguments.go | 33 ++ language/ast/definitions.go | 153 +++++++ language/ast/directives.go | 33 ++ language/ast/document.go | 31 ++ language/ast/location.go | 22 + language/ast/name.go | 31 ++ language/ast/node.go | 45 ++ language/ast/selections.go | 131 ++++++ language/ast/type_definitions.go | 402 ++++++++++++++++++ language/ast/types.go | 106 +++++ language/ast/values.go | 305 +++++++++++++ {kinds => language/kinds}/kinds.go | 0 lexer.go => language/lexer/lexer.go | 29 +- lexer_test.go => language/lexer/lexer_test.go | 12 +- location.go => language/location/location.go | 6 +- printer.go => language/printer/printer.go | 209 ++++----- .../printer/printer_test.go | 2 +- .../printer/schema_printer_test.go | 2 +- source.go => language/source/source.go | 2 +- visitor.go => language/visitor/visitor.go | 2 +- .../visitor/visitor_test.go | 47 +- lists_test.go | 67 +-- located.go | 13 +- mutations_test.go | 17 +- nonnull_test.go | 253 +++++------ parser.go | 359 ++++++++-------- parser_test.go | 119 +++--- scalars.go | 26 +- schema_parser_test.go | 399 ++++++++--------- testutil.go | 5 +- types.go | 8 +- validation_test.go | 8 +- validator.go | 9 +- values.go | 53 +-- variables_test.go | 104 ++--- 59 files changed, 2407 insertions(+), 2256 deletions(-) delete mode 100644 ast_arguments.go delete mode 100644 ast_definitions.go delete mode 100644 ast_directives.go delete mode 100644 ast_document.go delete mode 100644 ast_location.go delete mode 100644 ast_name.go delete mode 100644 ast_node.go delete mode 100644 ast_selections.go delete mode 100644 ast_type_definitions.go delete mode 100644 ast_types.go delete mode 100644 ast_values.go rename error.go => gqlerrors/error.go (65%) rename formatted.go => gqlerrors/formatted.go (84%) create mode 100644 gqlerrors/located.go rename sortutil.go => gqlerrors/sortutil.go (97%) rename syntax.go => gqlerrors/syntax.go (71%) create mode 100644 language/ast/arguments.go create mode 100644 language/ast/definitions.go create mode 100644 language/ast/directives.go create mode 100644 language/ast/document.go create mode 100644 language/ast/location.go create mode 100644 language/ast/name.go create mode 100644 language/ast/node.go create mode 100644 language/ast/selections.go create mode 100644 language/ast/type_definitions.go create mode 100644 language/ast/types.go create mode 100644 language/ast/values.go rename {kinds => language/kinds}/kinds.go (100%) rename lexer.go => language/lexer/lexer.go (91%) rename lexer_test.go => language/lexer/lexer_test.go (97%) rename location.go => language/location/location.go (80%) rename printer.go => language/printer/printer.go (56%) rename printer_test.go => language/printer/printer_test.go (99%) rename schema_printer_test.go => language/printer/schema_printer_test.go (99%) rename source.go => language/source/source.go (92%) rename visitor.go => language/visitor/visitor.go (99%) rename visitor_test.go => language/visitor/visitor_test.go (95%) diff --git a/abstract_test.go b/abstract_test.go index 7353afdc..98504b22 100644 --- a/abstract_test.go +++ b/abstract_test.go @@ -3,6 +3,9 @@ package graphql import ( "reflect" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/location" ) type testDog struct { @@ -438,10 +441,10 @@ func TestResolveTypeOnInterfaceYieldsUsefulError(t *testing.T) { nil, }, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Runtime Object type "Human" is not a possible type for "Pet".`, - Locations: []SourceLocation{}, + Locations: []location.SourceLocation{}, }, }, } @@ -596,10 +599,10 @@ func TestResolveTypeOnUnionYieldsUsefulError(t *testing.T) { nil, }, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Runtime Object type "Human" is not a possible type for "Pet".`, - Locations: []SourceLocation{}, + Locations: []location.SourceLocation{}, }, }, } diff --git a/ast_arguments.go b/ast_arguments.go deleted file mode 100644 index 1a245df0..00000000 --- a/ast_arguments.go +++ /dev/null @@ -1,33 +0,0 @@ -package graphql - -import ( - "github.com/chris-ramon/graphql/kinds" -) - -// Argument implements Node -type AstArgument struct { - Kind string - Loc *AstLocation - Name *AstName - Value Value -} - -func NewAstArgument(arg *AstArgument) *AstArgument { - if arg == nil { - arg = &AstArgument{} - } - return &AstArgument{ - Kind: kinds.Argument, - Loc: arg.Loc, - Name: arg.Name, - Value: arg.Value, - } -} - -func (arg *AstArgument) GetKind() string { - return arg.Kind -} - -func (arg *AstArgument) GetLoc() *AstLocation { - return arg.Loc -} diff --git a/ast_definitions.go b/ast_definitions.go deleted file mode 100644 index 631e6364..00000000 --- a/ast_definitions.go +++ /dev/null @@ -1,153 +0,0 @@ -package graphql - -import ( - "github.com/chris-ramon/graphql/kinds" -) - -type Definition interface { - // TODO: determine the minimal set of interface for `Definition` - GetOperation() string - GetVariableDefinitions() []*AstVariableDefinition - GetSelectionSet() *AstSelectionSet -} - -// Ensure that all definition types implements Definition interface -var _ Definition = (*AstOperationDefinition)(nil) -var _ Definition = (*AstFragmentDefinition)(nil) -var _ Definition = (Definition)(nil) - -// AstOperationDefinition implements Node, Definition -type AstOperationDefinition struct { - Kind string - Loc *AstLocation - Operation string - Name *AstName - VariableDefinitions []*AstVariableDefinition - Directives []*AstDirective - SelectionSet *AstSelectionSet -} - -func NewAstOperationDefinition(op *AstOperationDefinition) *AstOperationDefinition { - if op == nil { - op = &AstOperationDefinition{} - } - return &AstOperationDefinition{ - Kind: kinds.OperationDefinition, - Loc: op.Loc, - Operation: op.Operation, - Name: op.Name, - VariableDefinitions: op.VariableDefinitions, - Directives: op.Directives, - SelectionSet: op.SelectionSet, - } -} - -func (op *AstOperationDefinition) GetKind() string { - return op.Kind -} - -func (op *AstOperationDefinition) GetLoc() *AstLocation { - return op.Loc -} - -func (op *AstOperationDefinition) GetOperation() string { - return op.Operation -} - -func (op *AstOperationDefinition) GetName() *AstName { - return op.Name -} - -func (op *AstOperationDefinition) GetVariableDefinitions() []*AstVariableDefinition { - return op.VariableDefinitions -} - -func (op *AstOperationDefinition) GetDirectives() []*AstDirective { - return op.Directives -} - -func (op *AstOperationDefinition) GetSelectionSet() *AstSelectionSet { - return op.SelectionSet -} - -// AstFragmentDefinition implements Node, Definition -type AstFragmentDefinition struct { - Kind string - Loc *AstLocation - Operation string - Name *AstName - VariableDefinitions []*AstVariableDefinition - TypeCondition *AstNamed - Directives []*AstDirective - SelectionSet *AstSelectionSet -} - -func NewAstFragmentDefinition(fd *AstFragmentDefinition) *AstFragmentDefinition { - if fd == nil { - fd = &AstFragmentDefinition{} - } - return &AstFragmentDefinition{ - Kind: kinds.FragmentDefinition, - Loc: fd.Loc, - Operation: fd.Operation, - Name: fd.Name, - VariableDefinitions: fd.VariableDefinitions, - TypeCondition: fd.TypeCondition, - Directives: fd.Directives, - SelectionSet: fd.SelectionSet, - } -} - -func (fd *AstFragmentDefinition) GetKind() string { - return fd.Kind -} - -func (fd *AstFragmentDefinition) GetLoc() *AstLocation { - return fd.Loc -} - -func (fd *AstFragmentDefinition) GetOperation() string { - return fd.Operation -} - -func (fd *AstFragmentDefinition) GetName() *AstName { - return fd.Name -} - -func (fd *AstFragmentDefinition) GetVariableDefinitions() []*AstVariableDefinition { - return fd.VariableDefinitions -} - -func (fd *AstFragmentDefinition) GetSelectionSet() *AstSelectionSet { - return fd.SelectionSet -} - -// AstVariableDefinition implements Node -type AstVariableDefinition struct { - Kind string - Loc *AstLocation - Variable *AstVariable - Type AstType - DefaultValue Value -} - -func NewAstVariableDefinition(vd *AstVariableDefinition) *AstVariableDefinition { - if vd == nil { - vd = &AstVariableDefinition{} - } - return &AstVariableDefinition{ - Kind: kinds.VariableDefinition, - Loc: vd.Loc, - Variable: vd.Variable, - Type: vd.Type, - DefaultValue: vd.DefaultValue, - } -} - -func (vd *AstVariableDefinition) GetKind() string { - return vd.Kind -} - -func (vd *AstVariableDefinition) GetLoc() *AstLocation { - return vd.Loc -} diff --git a/ast_directives.go b/ast_directives.go deleted file mode 100644 index e9451154..00000000 --- a/ast_directives.go +++ /dev/null @@ -1,33 +0,0 @@ -package graphql - -import ( - "github.com/chris-ramon/graphql/kinds" -) - -// Directive implements Node -type AstDirective struct { - Kind string - Loc *AstLocation - Name *AstName - Arguments []*AstArgument -} - -func NewAstDirective(dir *AstDirective) *AstDirective { - if dir == nil { - dir = &AstDirective{} - } - return &AstDirective{ - Kind: kinds.Directive, - Loc: dir.Loc, - Name: dir.Name, - Arguments: dir.Arguments, - } -} - -func (dir *AstDirective) GetKind() string { - return dir.Kind -} - -func (dir *AstDirective) GetLoc() *AstLocation { - return dir.Loc -} diff --git a/ast_document.go b/ast_document.go deleted file mode 100644 index a7ca2148..00000000 --- a/ast_document.go +++ /dev/null @@ -1,31 +0,0 @@ -package graphql - -import ( - "github.com/chris-ramon/graphql/kinds" -) - -// Document implements Node -type AstDocument struct { - Kind string - Loc *AstLocation - Definitions []Node -} - -func NewAstDocument(d *AstDocument) *AstDocument { - if d == nil { - d = &AstDocument{} - } - return &AstDocument{ - Kind: kinds.Document, - Loc: d.Loc, - Definitions: d.Definitions, - } -} - -func (node *AstDocument) GetKind() string { - return node.Kind -} - -func (node *AstDocument) GetLoc() *AstLocation { - return node.Loc -} diff --git a/ast_location.go b/ast_location.go deleted file mode 100644 index aed1ddbf..00000000 --- a/ast_location.go +++ /dev/null @@ -1,18 +0,0 @@ -package graphql - -type AstLocation struct { - Start int - End int - Source *Source -} - -func NewAstLocation(loc *AstLocation) *AstLocation { - if loc == nil { - loc = &AstLocation{} - } - return &AstLocation{ - Start: loc.Start, - End: loc.End, - Source: loc.Source, - } -} diff --git a/ast_name.go b/ast_name.go deleted file mode 100644 index 55f81fc6..00000000 --- a/ast_name.go +++ /dev/null @@ -1,31 +0,0 @@ -package graphql - -import ( - "github.com/chris-ramon/graphql/kinds" -) - -// AstName implements Node -type AstName struct { - Kind string - Loc *AstLocation - Value string -} - -func NewAstName(node *AstName) *AstName { - if node == nil { - node = &AstName{} - } - return &AstName{ - Kind: kinds.Name, - Value: node.Value, - Loc: node.Loc, - } -} - -func (node *AstName) GetKind() string { - return node.Kind -} - -func (node *AstName) GetLoc() *AstLocation { - return node.Loc -} diff --git a/ast_node.go b/ast_node.go deleted file mode 100644 index af8e395e..00000000 --- a/ast_node.go +++ /dev/null @@ -1,45 +0,0 @@ -package graphql - -type Node interface { - GetKind() string - GetLoc() *AstLocation -} - -// The list of all possible AST node graphql. -// Ensure that all node types implements Node interface -var _ Node = (*AstName)(nil) -var _ Node = (*AstDocument)(nil) -var _ Node = (*AstOperationDefinition)(nil) -var _ Node = (*AstVariableDefinition)(nil) -var _ Node = (*AstVariable)(nil) -var _ Node = (*AstSelectionSet)(nil) -var _ Node = (*AstField)(nil) -var _ Node = (*AstArgument)(nil) -var _ Node = (*AstFragmentSpread)(nil) -var _ Node = (*AstInlineFragment)(nil) -var _ Node = (*AstFragmentDefinition)(nil) -var _ Node = (*AstIntValue)(nil) -var _ Node = (*AstFloatValue)(nil) -var _ Node = (*AstStringValue)(nil) -var _ Node = (*AstBooleanValue)(nil) -var _ Node = (*AstEnumValue)(nil) -var _ Node = (*AstListValue)(nil) -var _ Node = (*AstObjectValue)(nil) -var _ Node = (*AstObjectField)(nil) -var _ Node = (*AstDirective)(nil) -var _ Node = (*AstList)(nil) -var _ Node = (*AstNonNull)(nil) -var _ Node = (*AstObjectDefinition)(nil) -var _ Node = (*AstFieldDefinition)(nil) -var _ Node = (*AstInputValueDefinition)(nil) -var _ Node = (*AstInterfaceDefinition)(nil) -var _ Node = (*AstUnionDefinition)(nil) -var _ Node = (*AstScalarDefinition)(nil) -var _ Node = (*AstEnumDefinition)(nil) -var _ Node = (*AstEnumValueDefinition)(nil) -var _ Node = (*AstInputObjectDefinition)(nil) -var _ Node = (*AstTypeExtensionDefinition)(nil) - -// TODO: File issue in `graphql-js` where AstNamed is not -// defined as a Node. This might be a mistake in `graphql-js`? -var _ Node = (*AstNamed)(nil) diff --git a/ast_selections.go b/ast_selections.go deleted file mode 100644 index c3c8fd44..00000000 --- a/ast_selections.go +++ /dev/null @@ -1,131 +0,0 @@ -package graphql - -import ( - "github.com/chris-ramon/graphql/kinds" -) - -type Selection interface { -} - -// Ensure that all definition types implements Selection interface -var _ Selection = (*AstField)(nil) -var _ Selection = (*AstFragmentSpread)(nil) -var _ Selection = (*AstInlineFragment)(nil) - -// AstField implements Node, Selection -type AstField struct { - Kind string - Loc *AstLocation - Alias *AstName - Name *AstName - Arguments []*AstArgument - Directives []*AstDirective - SelectionSet *AstSelectionSet -} - -func NewField(f *AstField) *AstField { - if f == nil { - f = &AstField{} - } - return &AstField{ - Kind: kinds.Field, - Loc: f.Loc, - Alias: f.Alias, - Name: f.Name, - Arguments: f.Arguments, - Directives: f.Directives, - SelectionSet: f.SelectionSet, - } -} - -func (f *AstField) GetKind() string { - return f.Kind -} - -func (f *AstField) GetLoc() *AstLocation { - return f.Loc -} - -// FragmentSpread implements Node, Selection -type AstFragmentSpread struct { - Kind string - Loc *AstLocation - Name *AstName - Directives []*AstDirective -} - -func NewAstFragmentSpread(fs *AstFragmentSpread) *AstFragmentSpread { - if fs == nil { - fs = &AstFragmentSpread{} - } - return &AstFragmentSpread{ - Kind: kinds.FragmentSpread, - Loc: fs.Loc, - Name: fs.Name, - Directives: fs.Directives, - } -} - -func (fs *AstFragmentSpread) GetKind() string { - return fs.Kind -} - -func (fs *AstFragmentSpread) GetLoc() *AstLocation { - return fs.Loc -} - -// InlineFragment implements Node, Selection -type AstInlineFragment struct { - Kind string - Loc *AstLocation - TypeCondition *AstNamed - Directives []*AstDirective - SelectionSet *AstSelectionSet -} - -func NewAstInlineFragment(f *AstInlineFragment) *AstInlineFragment { - if f == nil { - f = &AstInlineFragment{} - } - return &AstInlineFragment{ - Kind: kinds.InlineFragment, - Loc: f.Loc, - TypeCondition: f.TypeCondition, - Directives: f.Directives, - SelectionSet: f.SelectionSet, - } -} - -func (f *AstInlineFragment) GetKind() string { - return f.Kind -} - -func (f *AstInlineFragment) GetLoc() *AstLocation { - return f.Loc -} - -// AstSelectionSet implements Node -type AstSelectionSet struct { - Kind string - Loc *AstLocation - Selections []Selection -} - -func NewAstSelectionSet(ss *AstSelectionSet) *AstSelectionSet { - if ss == nil { - ss = &AstSelectionSet{} - } - return &AstSelectionSet{ - Kind: kinds.SelectionSet, - Loc: ss.Loc, - Selections: ss.Selections, - } -} - -func (ss *AstSelectionSet) GetKind() string { - return ss.Kind -} - -func (ss *AstSelectionSet) GetLoc() *AstLocation { - return ss.Loc -} diff --git a/ast_type_definitions.go b/ast_type_definitions.go deleted file mode 100644 index 2978e78b..00000000 --- a/ast_type_definitions.go +++ /dev/null @@ -1,402 +0,0 @@ -package graphql - -import ( - "github.com/chris-ramon/graphql/kinds" -) - -// Ensure that all typeDefinition types implements Definition interface -var _ Definition = (*AstObjectDefinition)(nil) -var _ Definition = (*AstInterfaceDefinition)(nil) -var _ Definition = (*AstUnionDefinition)(nil) -var _ Definition = (*AstScalarDefinition)(nil) -var _ Definition = (*AstEnumDefinition)(nil) -var _ Definition = (*AstInputObjectDefinition)(nil) -var _ Definition = (*AstTypeExtensionDefinition)(nil) - -// AstObjectDefinition implements Node, Definition -type AstObjectDefinition struct { - Kind string - Loc *AstLocation - Name *AstName - Interfaces []*AstNamed - Fields []*AstFieldDefinition -} - -func NewAstObjectDefinition(def *AstObjectDefinition) *AstObjectDefinition { - if def == nil { - def = &AstObjectDefinition{} - } - return &AstObjectDefinition{ - Kind: kinds.ObjectDefinition, - Loc: def.Loc, - Name: def.Name, - Interfaces: def.Interfaces, - Fields: def.Fields, - } -} - -func (def *AstObjectDefinition) GetKind() string { - return def.Kind -} - -func (def *AstObjectDefinition) GetLoc() *AstLocation { - return def.Loc -} - -func (def *AstObjectDefinition) GetName() *AstName { - return def.Name -} - -func (def *AstObjectDefinition) GetVariableDefinitions() []*AstVariableDefinition { - return []*AstVariableDefinition{} -} - -func (def *AstObjectDefinition) GetSelectionSet() *AstSelectionSet { - return &AstSelectionSet{} -} - -func (def *AstObjectDefinition) GetOperation() string { - return "" -} - -// AstFieldDefinition implements Node -type AstFieldDefinition struct { - Kind string - Loc *AstLocation - Name *AstName - Arguments []*AstInputValueDefinition - Type AstType -} - -func NewAstFieldDefinition(def *AstFieldDefinition) *AstFieldDefinition { - if def == nil { - def = &AstFieldDefinition{} - } - return &AstFieldDefinition{ - Kind: kinds.FieldDefinition, - Loc: def.Loc, - Name: def.Name, - Arguments: def.Arguments, - Type: def.Type, - } -} - -func (def *AstFieldDefinition) GetKind() string { - return def.Kind -} - -func (def *AstFieldDefinition) GetLoc() *AstLocation { - return def.Loc -} - -// AstInputValueDefinition implements Node -type AstInputValueDefinition struct { - Kind string - Loc *AstLocation - Name *AstName - Type AstType - DefaultValue Value -} - -func NewAstInputValueDefinition(def *AstInputValueDefinition) *AstInputValueDefinition { - if def == nil { - def = &AstInputValueDefinition{} - } - return &AstInputValueDefinition{ - Kind: kinds.InputValueDefinition, - Loc: def.Loc, - Name: def.Name, - Type: def.Type, - DefaultValue: def.DefaultValue, - } -} - -func (def *AstInputValueDefinition) GetKind() string { - return def.Kind -} - -func (def *AstInputValueDefinition) GetLoc() *AstLocation { - return def.Loc -} - -// AstInterfaceDefinition implements Node, Definition -type AstInterfaceDefinition struct { - Kind string - Loc *AstLocation - Name *AstName - Fields []*AstFieldDefinition -} - -func NewAstInterfaceDefinition(def *AstInterfaceDefinition) *AstInterfaceDefinition { - if def == nil { - def = &AstInterfaceDefinition{} - } - return &AstInterfaceDefinition{ - Kind: kinds.InterfaceDefinition, - Loc: def.Loc, - Name: def.Name, - Fields: def.Fields, - } -} - -func (def *AstInterfaceDefinition) GetKind() string { - return def.Kind -} - -func (def *AstInterfaceDefinition) GetLoc() *AstLocation { - return def.Loc -} - -func (def *AstInterfaceDefinition) GetName() *AstName { - return def.Name -} - -func (def *AstInterfaceDefinition) GetVariableDefinitions() []*AstVariableDefinition { - return []*AstVariableDefinition{} -} - -func (def *AstInterfaceDefinition) GetSelectionSet() *AstSelectionSet { - return &AstSelectionSet{} -} - -func (def *AstInterfaceDefinition) GetOperation() string { - return "" -} - -// AstUnionDefinition implements Node, Definition -type AstUnionDefinition struct { - Kind string - Loc *AstLocation - Name *AstName - Types []*AstNamed -} - -func NewAstUnionDefinition(def *AstUnionDefinition) *AstUnionDefinition { - if def == nil { - def = &AstUnionDefinition{} - } - return &AstUnionDefinition{ - Kind: kinds.UnionDefinition, - Loc: def.Loc, - Name: def.Name, - Types: def.Types, - } -} - -func (def *AstUnionDefinition) GetKind() string { - return def.Kind -} - -func (def *AstUnionDefinition) GetLoc() *AstLocation { - return def.Loc -} - -func (def *AstUnionDefinition) GetName() *AstName { - return def.Name -} - -func (def *AstUnionDefinition) GetVariableDefinitions() []*AstVariableDefinition { - return []*AstVariableDefinition{} -} - -func (def *AstUnionDefinition) GetSelectionSet() *AstSelectionSet { - return &AstSelectionSet{} -} - -func (def *AstUnionDefinition) GetOperation() string { - return "" -} - -// AstScalarDefinition implements Node, Definition -type AstScalarDefinition struct { - Kind string - Loc *AstLocation - Name *AstName -} - -func NewAstScalarDefinition(def *AstScalarDefinition) *AstScalarDefinition { - if def == nil { - def = &AstScalarDefinition{} - } - return &AstScalarDefinition{ - Kind: kinds.ScalarDefinition, - Loc: def.Loc, - Name: def.Name, - } -} - -func (def *AstScalarDefinition) GetKind() string { - return def.Kind -} - -func (def *AstScalarDefinition) GetLoc() *AstLocation { - return def.Loc -} - -func (def *AstScalarDefinition) GetName() *AstName { - return def.Name -} - -func (def *AstScalarDefinition) GetVariableDefinitions() []*AstVariableDefinition { - return []*AstVariableDefinition{} -} - -func (def *AstScalarDefinition) GetSelectionSet() *AstSelectionSet { - return &AstSelectionSet{} -} - -func (def *AstScalarDefinition) GetOperation() string { - return "" -} - -// AstEnumDefinition implements Node, Definition -type AstEnumDefinition struct { - Kind string - Loc *AstLocation - Name *AstName - Values []*AstEnumValueDefinition -} - -func NewAstEnumDefinition(def *AstEnumDefinition) *AstEnumDefinition { - if def == nil { - def = &AstEnumDefinition{} - } - return &AstEnumDefinition{ - Kind: kinds.EnumDefinition, - Loc: def.Loc, - Name: def.Name, - Values: def.Values, - } -} - -func (def *AstEnumDefinition) GetKind() string { - return def.Kind -} - -func (def *AstEnumDefinition) GetLoc() *AstLocation { - return def.Loc -} - -func (def *AstEnumDefinition) GetName() *AstName { - return def.Name -} - -func (def *AstEnumDefinition) GetVariableDefinitions() []*AstVariableDefinition { - return []*AstVariableDefinition{} -} - -func (def *AstEnumDefinition) GetSelectionSet() *AstSelectionSet { - return &AstSelectionSet{} -} - -func (def *AstEnumDefinition) GetOperation() string { - return "" -} - -// EnumValueDefinition implements Node, Definition -type AstEnumValueDefinition struct { - Kind string - Loc *AstLocation - Name *AstName -} - -func NewAstEnumValueDefinition(def *AstEnumValueDefinition) *AstEnumValueDefinition { - if def == nil { - def = &AstEnumValueDefinition{} - } - return &AstEnumValueDefinition{ - Kind: kinds.EnumValueDefinition, - Loc: def.Loc, - Name: def.Name, - } -} - -func (def *AstEnumValueDefinition) GetKind() string { - return def.Kind -} - -func (def *AstEnumValueDefinition) GetLoc() *AstLocation { - return def.Loc -} - -// AstInputObjectDefinition implements Node, Definition -type AstInputObjectDefinition struct { - Kind string - Loc *AstLocation - Name *AstName - Fields []*AstInputValueDefinition -} - -func NewAstInputObjectDefinition(def *AstInputObjectDefinition) *AstInputObjectDefinition { - if def == nil { - def = &AstInputObjectDefinition{} - } - return &AstInputObjectDefinition{ - Kind: kinds.InputObjectDefinition, - Loc: def.Loc, - Name: def.Name, - Fields: def.Fields, - } -} - -func (def *AstInputObjectDefinition) GetKind() string { - return def.Kind -} - -func (def *AstInputObjectDefinition) GetLoc() *AstLocation { - return def.Loc -} - -func (def *AstInputObjectDefinition) GetName() *AstName { - return def.Name -} - -func (def *AstInputObjectDefinition) GetVariableDefinitions() []*AstVariableDefinition { - return []*AstVariableDefinition{} -} - -func (def *AstInputObjectDefinition) GetSelectionSet() *AstSelectionSet { - return &AstSelectionSet{} -} - -func (def *AstInputObjectDefinition) GetOperation() string { - return "" -} - -// TypeExtensionDefinition implements Node, Definition -type AstTypeExtensionDefinition struct { - Kind string - Loc *AstLocation - Definition *AstObjectDefinition -} - -func NewAstTypeExtensionDefinition(def *AstTypeExtensionDefinition) *AstTypeExtensionDefinition { - if def == nil { - def = &AstTypeExtensionDefinition{} - } - return &AstTypeExtensionDefinition{ - Kind: kinds.TypeExtensionDefinition, - Loc: def.Loc, - Definition: def.Definition, - } -} - -func (def *AstTypeExtensionDefinition) GetKind() string { - return def.Kind -} - -func (def *AstTypeExtensionDefinition) GetLoc() *AstLocation { - return def.Loc -} - -func (def *AstTypeExtensionDefinition) GetVariableDefinitions() []*AstVariableDefinition { - return []*AstVariableDefinition{} -} - -func (def *AstTypeExtensionDefinition) GetSelectionSet() *AstSelectionSet { - return &AstSelectionSet{} -} - -func (def *AstTypeExtensionDefinition) GetOperation() string { - return "" -} diff --git a/ast_types.go b/ast_types.go deleted file mode 100644 index 37537a90..00000000 --- a/ast_types.go +++ /dev/null @@ -1,106 +0,0 @@ -package graphql - -import ( - "github.com/chris-ramon/graphql/kinds" -) - -type AstType interface { - GetKind() string - GetLoc() *AstLocation - String() string -} - -// Ensure that all value types implements Value interface -var _ AstType = (*AstNamed)(nil) -var _ AstType = (*AstList)(nil) -var _ AstType = (*AstNonNull)(nil) - -// AstNamed implements Node, Type -type AstNamed struct { - Kind string - Loc *AstLocation - Name *AstName -} - -func NewAstNamed(t *AstNamed) *AstNamed { - if t == nil { - t = &AstNamed{} - } - return &AstNamed{ - Kind: kinds.Named, - Loc: t.Loc, - Name: t.Name, - } -} - -func (t *AstNamed) GetKind() string { - return t.Kind -} - -func (t *AstNamed) GetLoc() *AstLocation { - return t.Loc -} - -func (t *AstNamed) String() string { - return t.GetKind() -} - -// List implements Node, Type -type AstList struct { - Kind string - Loc *AstLocation - Type AstType -} - -func NewAstList(t *AstList) *AstList { - if t == nil { - t = &AstList{} - } - return &AstList{ - Kind: kinds.List, - Loc: t.Loc, - Type: t.Type, - } -} - -func (t *AstList) GetKind() string { - return t.Kind -} - -func (t *AstList) GetLoc() *AstLocation { - return t.Loc -} - -func (t *AstList) String() string { - return t.GetKind() -} - -// AstNonNull implements Node, Type -type AstNonNull struct { - Kind string - Loc *AstLocation - Type AstType -} - -func NewAstNonNull(t *AstNonNull) *AstNonNull { - if t == nil { - t = &AstNonNull{} - } - return &AstNonNull{ - Kind: kinds.NonNull, - Loc: t.Loc, - Type: t.Type, - } -} - -func (t *AstNonNull) GetKind() string { - return t.Kind -} - -func (t *AstNonNull) GetLoc() *AstLocation { - return t.Loc -} - -func (t *AstNonNull) String() string { - return t.GetKind() -} diff --git a/ast_values.go b/ast_values.go deleted file mode 100644 index 7c8d84b4..00000000 --- a/ast_values.go +++ /dev/null @@ -1,305 +0,0 @@ -package graphql - -import ( - "github.com/chris-ramon/graphql/kinds" -) - -type Value interface { - GetValue() interface{} - GetKind() string - GetLoc() *AstLocation -} - -// Ensure that all value types implements Value interface -var _ Value = (*AstVariable)(nil) -var _ Value = (*AstIntValue)(nil) -var _ Value = (*AstFloatValue)(nil) -var _ Value = (*AstStringValue)(nil) -var _ Value = (*AstBooleanValue)(nil) -var _ Value = (*AstEnumValue)(nil) -var _ Value = (*AstListValue)(nil) -var _ Value = (*AstObjectValue)(nil) - -// AstVariable implements Node, Value -type AstVariable struct { - Kind string - Loc *AstLocation - Name *AstName -} - -func NewAstVariable(v *AstVariable) *AstVariable { - if v == nil { - v = &AstVariable{} - } - return &AstVariable{ - Kind: kinds.Variable, - Loc: v.Loc, - Name: v.Name, - } -} - -func (v *AstVariable) GetKind() string { - return v.Kind -} - -func (v *AstVariable) GetLoc() *AstLocation { - return v.Loc -} - -// GetValue alias to AstVariable.GetName() -func (v *AstVariable) GetValue() interface{} { - return v.GetName() -} - -func (v *AstVariable) GetName() interface{} { - return v.Name -} - -// AstIntValue implements Node, Value -type AstIntValue struct { - Kind string - Loc *AstLocation - Value string -} - -func NewAstIntValue(v *AstIntValue) *AstIntValue { - if v == nil { - v = &AstIntValue{} - } - return &AstIntValue{ - Kind: kinds.IntValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *AstIntValue) GetKind() string { - return v.Kind -} - -func (v *AstIntValue) GetLoc() *AstLocation { - return v.Loc -} - -func (v *AstIntValue) GetValue() interface{} { - return v.Value -} - -// AstFloatValue implements Node, Value -type AstFloatValue struct { - Kind string - Loc *AstLocation - Value string -} - -func NewAstFloatValue(v *AstFloatValue) *AstFloatValue { - if v == nil { - v = &AstFloatValue{} - } - return &AstFloatValue{ - Kind: kinds.FloatValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *AstFloatValue) GetKind() string { - return v.Kind -} - -func (v *AstFloatValue) GetLoc() *AstLocation { - return v.Loc -} - -func (v *AstFloatValue) GetValue() interface{} { - return v.Value -} - -// AstStringValue implements Node, Value -type AstStringValue struct { - Kind string - Loc *AstLocation - Value string -} - -func NewAstStringValue(v *AstStringValue) *AstStringValue { - if v == nil { - v = &AstStringValue{} - } - return &AstStringValue{ - Kind: kinds.StringValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *AstStringValue) GetKind() string { - return v.Kind -} - -func (v *AstStringValue) GetLoc() *AstLocation { - return v.Loc -} - -func (v *AstStringValue) GetValue() interface{} { - return v.Value -} - -// AstBooleanValue implements Node, Value -type AstBooleanValue struct { - Kind string - Loc *AstLocation - Value bool -} - -func NewAstBooleanValue(v *AstBooleanValue) *AstBooleanValue { - if v == nil { - v = &AstBooleanValue{} - } - return &AstBooleanValue{ - Kind: kinds.BooleanValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *AstBooleanValue) GetKind() string { - return v.Kind -} - -func (v *AstBooleanValue) GetLoc() *AstLocation { - return v.Loc -} - -func (v *AstBooleanValue) GetValue() interface{} { - return v.Value -} - -// AstEnumValue implements Node, Value -type AstEnumValue struct { - Kind string - Loc *AstLocation - Value string -} - -func NewAstEnumValue(v *AstEnumValue) *AstEnumValue { - if v == nil { - v = &AstEnumValue{} - } - return &AstEnumValue{ - Kind: kinds.EnumValue, - Loc: v.Loc, - Value: v.Value, - } -} - -func (v *AstEnumValue) GetKind() string { - return v.Kind -} - -func (v *AstEnumValue) GetLoc() *AstLocation { - return v.Loc -} - -func (v *AstEnumValue) GetValue() interface{} { - return v.Value -} - -// AstListValue implements Node, Value -type AstListValue struct { - Kind string - Loc *AstLocation - Values []Value -} - -func NewAstListValue(v *AstListValue) *AstListValue { - if v == nil { - v = &AstListValue{} - } - return &AstListValue{ - Kind: kinds.ListValue, - Loc: v.Loc, - Values: v.Values, - } -} - -func (v *AstListValue) GetKind() string { - return v.Kind -} - -func (v *AstListValue) GetLoc() *AstLocation { - return v.Loc -} - -// GetValue alias to AstListValue.GetValues() -func (v *AstListValue) GetValue() interface{} { - return v.GetValues() -} - -func (v *AstListValue) GetValues() interface{} { - // TODO: verify AstObjectValue.GetValue() - return v.Values -} - -// AstObjectValue implements Node, Value -type AstObjectValue struct { - Kind string - Loc *AstLocation - Fields []*AstObjectField -} - -func NewAstObjectValue(v *AstObjectValue) *AstObjectValue { - if v == nil { - v = &AstObjectValue{} - } - return &AstObjectValue{ - Kind: kinds.ObjectValue, - Loc: v.Loc, - Fields: v.Fields, - } -} - -func (v *AstObjectValue) GetKind() string { - return v.Kind -} - -func (v *AstObjectValue) GetLoc() *AstLocation { - return v.Loc -} - -func (v *AstObjectValue) GetValue() interface{} { - // TODO: verify AstObjectValue.GetValue() - return v.Fields -} - -// AstObjectField implements Node, Value -type AstObjectField struct { - Kind string - Name *AstName - Loc *AstLocation - Value Value -} - -func NewAstObjectField(f *AstObjectField) *AstObjectField { - if f == nil { - f = &AstObjectField{} - } - return &AstObjectField{ - Kind: kinds.ObjectField, - Loc: f.Loc, - Name: f.Name, - Value: f.Value, - } -} - -func (f *AstObjectField) GetKind() string { - return f.Kind -} - -func (f *AstObjectField) GetLoc() *AstLocation { - return f.Loc -} - -func (f *AstObjectField) GetValue() interface{} { - return f.Value -} diff --git a/definition.go b/definition.go index 77f9aa13..c1f0b126 100644 --- a/definition.go +++ b/definition.go @@ -5,6 +5,8 @@ import ( "fmt" "reflect" "regexp" + + "github.com/chris-ramon/graphql/language/ast" ) // These are all of the possible kinds of @@ -162,7 +164,7 @@ type Scalar struct { } type SerializeFn func(value interface{}) interface{} type ParseValueFn func(value interface{}) interface{} -type ParseLiteralFn func(valueAST Value) interface{} +type ParseLiteralFn func(valueAST ast.Value) interface{} type ScalarConfig struct { Name string `json:"name"` Description string `json:"description"` @@ -224,7 +226,7 @@ func (st *Scalar) ParseValue(value interface{}) interface{} { } return st.scalarConfig.ParseValue(value) } -func (st *Scalar) ParseLiteral(valueAST Value) interface{} { +func (st *Scalar) ParseLiteral(valueAST ast.Value) interface{} { if st.scalarConfig.ParseLiteral == nil { return nil } @@ -500,13 +502,13 @@ type FieldResolveFn func(p GQLFRParams) interface{} type ResolveInfo struct { FieldName string - FieldASTs []*AstField + FieldASTs []*ast.Field ReturnType Output ParentType Composite Schema Schema - Fragments map[string]Definition + Fragments map[string]ast.Definition RootValue interface{} - Operation Definition + Operation ast.Definition VariableValues map[string]interface{} } @@ -954,8 +956,8 @@ func (gt *Enum) ParseValue(value interface{}) interface{} { } return nil } -func (gt *Enum) ParseLiteral(valueAST Value) interface{} { - if valueAST, ok := valueAST.(*AstEnumValue); ok { +func (gt *Enum) ParseLiteral(valueAST ast.Value) interface{} { + if valueAST, ok := valueAST.(*ast.EnumValue); ok { if enumValue, ok := gt.getNameLookup()[valueAST.Value]; ok { return enumValue.Value } diff --git a/enum_type_test.go b/enum_type_test.go index 02ad10df..b0198e75 100644 --- a/enum_type_test.go +++ b/enum_type_test.go @@ -3,6 +3,8 @@ package graphql import ( "reflect" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" ) var enumTypeTestColorType = NewEnum(EnumConfig{ @@ -150,8 +152,8 @@ func TestTypeSystem_EnumValues_DoesNotAcceptStringLiterals(t *testing.T) { query := `{ colorEnum(fromEnum: "GREEN") }` expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Argument "fromEnum" expected type "Color" but got: "GREEN".`, }, }, @@ -178,8 +180,8 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueInPlaceOfEnumLiteral(t query := `{ colorEnum(fromEnum: 1) }` expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Argument "fromEnum" expected type "Color" but got: 1.`, }, }, @@ -195,8 +197,8 @@ func TestTypeSystem_EnumValues_DoesNotAcceptEnumLiteralInPlaceOfInt(t *testing.T query := `{ colorEnum(fromInt: GREEN) }` expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Argument "fromInt" expected type "Int" but got: GREEN.`, }, }, @@ -246,8 +248,8 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueAsEnumVariable(t *testi } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$color" expected value of type "Color!" but got: 2.`, }, }, @@ -265,8 +267,8 @@ func TestTypeSystem_EnumValues_DoesNotAcceptStringVariablesAsEnumInput(t *testin } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$color" of type "String!" used in position expecting type "Color".`, }, }, @@ -284,8 +286,8 @@ func TestTypeSystem_EnumValues_DoesNotAcceptInternalValueVariableAsEnumInput(t * } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$color" of type "Int!" used in position expecting type "Color".`, }, }, diff --git a/executor.go b/executor.go index c3fde1cf..e7014f58 100644 --- a/executor.go +++ b/executor.go @@ -2,21 +2,23 @@ package graphql import ( "fmt" - "reflect" "strings" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/ast" ) type ExecuteParams struct { Schema Schema Root interface{} - AST *AstDocument + AST *ast.Document OperationName string Args map[string]interface{} } func Execute(p ExecuteParams, resultChan chan *Result) { - var errors []FormattedError + var errors []gqlerrors.FormattedError var result Result params := BuildExecutionCtxParams{ Schema: p.Schema, @@ -36,9 +38,9 @@ func Execute(p ExecuteParams, resultChan chan *Result) { if r := recover(); r != nil { var err error if r, ok := r.(error); ok { - err = FormatError(r) + err = gqlerrors.FormatError(r) } - exeContext.Errors = append(exeContext.Errors, FormatError(err)) + exeContext.Errors = append(exeContext.Errors, gqlerrors.FormatError(err)) result.Errors = exeContext.Errors resultChan <- &result } @@ -54,42 +56,42 @@ func Execute(p ExecuteParams, resultChan chan *Result) { type BuildExecutionCtxParams struct { Schema Schema Root interface{} - AST *AstDocument + AST *ast.Document OperationName string Args map[string]interface{} - Errors []FormattedError + Errors []gqlerrors.FormattedError Result *Result ResultChan chan *Result } type ExecutionContext struct { Schema Schema - Fragments map[string]Definition + Fragments map[string]ast.Definition Root interface{} - Operation Definition + Operation ast.Definition VariableValues map[string]interface{} - Errors []FormattedError + Errors []gqlerrors.FormattedError } func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { eCtx := &ExecutionContext{} - operations := map[string]Definition{} - fragments := map[string]Definition{} + operations := map[string]ast.Definition{} + fragments := map[string]ast.Definition{} for _, statement := range p.AST.Definitions { switch stm := statement.(type) { - case *AstOperationDefinition: + case *ast.OperationDefinition: key := "" if stm.GetName() != nil && stm.GetName().Value != "" { key = stm.GetName().Value } operations[key] = stm - case *AstFragmentDefinition: + case *ast.FragmentDefinition: key := "" if stm.GetName() != nil && stm.GetName().Value != "" { key = stm.GetName().Value } fragments[key] = stm default: - err := NewFormattedError( + err := gqlerrors.NewFormattedError( fmt.Sprintf("GraphQL cannot execute a request containing a %v", statement.GetKind()), ) p.Result.Errors = append(p.Result.Errors, err) @@ -98,7 +100,7 @@ func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { } } if (p.OperationName == "") && (len(operations) != 1) { - err := NewFormattedError("Must provide operation name if query contains multiple operations.") + err := gqlerrors.NewFormattedError("Must provide operation name if query contains multiple operations.") p.Result.Errors = append(p.Result.Errors, err) p.ResultChan <- p.Result return eCtx @@ -113,14 +115,14 @@ func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { } operation, found := operations[opName] if !found { - err := NewFormattedError(fmt.Sprintf(`Unknown operation named "%v".`, opName)) + err := gqlerrors.NewFormattedError(fmt.Sprintf(`Unknown operation named "%v".`, opName)) p.Result.Errors = append(p.Result.Errors, err) p.ResultChan <- p.Result return eCtx } variableValues, err := getVariableValues(p.Schema, operation.GetVariableDefinitions(), p.Args) if err != nil { - p.Result.Errors = append(p.Result.Errors, FormatError(err)) + p.Result.Errors = append(p.Result.Errors, gqlerrors.FormatError(err)) p.ResultChan <- p.Result return eCtx } @@ -137,7 +139,7 @@ func buildExecutionContext(p BuildExecutionCtxParams) *ExecutionContext { type ExecuteOperationParams struct { ExecutionContext *ExecutionContext Root interface{} - Operation Definition + Operation ast.Definition } func executeOperation(p ExecuteOperationParams, resultChan chan *Result) { @@ -166,10 +168,10 @@ func executeOperation(p ExecuteOperationParams, resultChan chan *Result) { } // Extracts the root type of the operation from the schema. -func getOperationRootType(schema Schema, operation Definition, r chan *Result) (objType *Object) { +func getOperationRootType(schema Schema, operation ast.Definition, r chan *Result) (objType *Object) { if operation == nil { var result Result - err := NewFormattedError("Can only execute queries and mutations") + err := gqlerrors.NewFormattedError("Can only execute queries and mutations") result.Errors = append(result.Errors, err) r <- &result return objType @@ -181,7 +183,7 @@ func getOperationRootType(schema Schema, operation Definition, r chan *Result) ( mutationType := schema.GetMutationType() if mutationType.Name == "" { var result Result - err := NewFormattedError("Schema is not configured for mutations") + err := gqlerrors.NewFormattedError("Schema is not configured for mutations") result.Errors = append(result.Errors, err) r <- &result return objType @@ -189,7 +191,7 @@ func getOperationRootType(schema Schema, operation Definition, r chan *Result) ( return mutationType default: var result Result - err := NewFormattedError("Can only execute queries and mutations") + err := gqlerrors.NewFormattedError("Can only execute queries and mutations") result.Errors = append(result.Errors, err) r <- &result return objType @@ -200,7 +202,7 @@ type ExecuteFieldsParams struct { ExecutionContext *ExecutionContext ParentType *Object Source interface{} - Fields map[string][]*AstField + Fields map[string][]*ast.Field } // Implements the "Evaluating selection sets" section of the spec for "write" mode. @@ -209,7 +211,7 @@ func executeFieldsSerially(p ExecuteFieldsParams, resultChan chan *Result) { p.Source = map[string]interface{}{} } if p.Fields == nil { - p.Fields = map[string][]*AstField{} + p.Fields = map[string][]*ast.Field{} } var result Result @@ -232,7 +234,7 @@ func executeFields(p ExecuteFieldsParams) (result Result) { p.Source = map[string]interface{}{} } if p.Fields == nil { - p.Fields = map[string][]*AstField{} + p.Fields = map[string][]*ast.Field{} } finalResults := map[string]interface{}{} for responseName, fieldASTs := range p.Fields { @@ -252,18 +254,18 @@ func executeFields(p ExecuteFieldsParams) (result Result) { type CollectFieldsParams struct { ExeContext *ExecutionContext OperationType *Object - SelectionSet *AstSelectionSet - Fields map[string][]*AstField + SelectionSet *ast.SelectionSet + Fields map[string][]*ast.Field VisitedFragmentNames map[string]bool } // Given a selectionSet, adds all of the fields in that selection to // the passed in map of fields, and returns it at the end. -func collectFields(p CollectFieldsParams) map[string][]*AstField { +func collectFields(p CollectFieldsParams) map[string][]*ast.Field { fields := p.Fields if fields == nil { - fields = map[string][]*AstField{} + fields = map[string][]*ast.Field{} } if p.VisitedFragmentNames == nil { p.VisitedFragmentNames = map[string]bool{} @@ -273,16 +275,16 @@ func collectFields(p CollectFieldsParams) map[string][]*AstField { } for _, iSelection := range p.SelectionSet.Selections { switch selection := iSelection.(type) { - case *AstField: + case *ast.Field: if !shouldIncludeNode(p.ExeContext, selection.Directives) { continue } name := getFieldEntryKey(selection) if _, ok := fields[name]; !ok { - fields[name] = []*AstField{} + fields[name] = []*ast.Field{} } fields[name] = append(fields[name], selection) - case *AstInlineFragment: + case *ast.InlineFragment: if !shouldIncludeNode(p.ExeContext, selection.Directives) || !doesFragmentConditionMatch(p.ExeContext, selection, p.OperationType) { @@ -296,7 +298,7 @@ func collectFields(p CollectFieldsParams) map[string][]*AstField { VisitedFragmentNames: p.VisitedFragmentNames, } collectFields(innerParams) - case *AstFragmentSpread: + case *ast.FragmentSpread: fragName := "" if selection.Name != nil { fragName = selection.Name.Value @@ -311,7 +313,7 @@ func collectFields(p CollectFieldsParams) map[string][]*AstField { continue } - if fragment, ok := fragment.(*AstFragmentDefinition); ok { + if fragment, ok := fragment.(*ast.FragmentDefinition); ok { if !shouldIncludeNode(p.ExeContext, fragment.Directives) || !doesFragmentConditionMatch(p.ExeContext, fragment, p.OperationType) { continue @@ -332,12 +334,12 @@ func collectFields(p CollectFieldsParams) map[string][]*AstField { // Determines if a field should be included based on the @include and @skip // directives, where @skip has higher precedence than @include. -func shouldIncludeNode(eCtx *ExecutionContext, directives []*AstDirective) bool { +func shouldIncludeNode(eCtx *ExecutionContext, directives []*ast.Directive) bool { defaultReturnValue := true - var skipAST *AstDirective - var includeAST *AstDirective + var skipAST *ast.Directive + var includeAST *ast.Directive for _, directive := range directives { if directive == nil || directive.Name == nil { continue @@ -392,10 +394,10 @@ func shouldIncludeNode(eCtx *ExecutionContext, directives []*AstDirective) bool } // Determines if a fragment is applicable to the given type. -func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment Node, ttype *Object) bool { +func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment ast.Node, ttype *Object) bool { switch fragment := fragment.(type) { - case *AstFragmentDefinition: + case *ast.FragmentDefinition: conditionalType, err := typeFromAST(eCtx.Schema, fragment.TypeCondition) if err != nil { return false @@ -407,7 +409,7 @@ func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment Node, ttype *Ob if conditionalType, ok := conditionalType.(Abstract); ok { return conditionalType.IsPossibleType(ttype) } - case *AstInlineFragment: + case *ast.InlineFragment: conditionalType, err := typeFromAST(eCtx.Schema, fragment.TypeCondition) if err != nil { return false @@ -425,7 +427,7 @@ func doesFragmentConditionMatch(eCtx *ExecutionContext, fragment Node, ttype *Ob } // Implements the logic to compute the key of a given field’s entry -func getFieldEntryKey(node *AstField) string { +func getFieldEntryKey(node *ast.Field) string { if node.Alias != nil && node.Alias.Value != "" { return node.Alias.Value @@ -447,7 +449,7 @@ type resolveFieldResultState struct { * then calls completeValue to complete promises, serialize scalars, or execute * the sub-selection-set for objects. */ -func resolveField(eCtx *ExecutionContext, parentType *Object, source interface{}, fieldASTs []*AstField) (result interface{}, resultState resolveFieldResultState) { +func resolveField(eCtx *ExecutionContext, parentType *Object, source interface{}, fieldASTs []*ast.Field) (result interface{}, resultState resolveFieldResultState) { // catch panic from resolveFn var returnType Output defer func() (interface{}, resolveFieldResultState) { @@ -461,13 +463,13 @@ func resolveField(eCtx *ExecutionContext, parentType *Object, source interface{} ) } if r, ok := r.(error); ok { - err = FormatError(r) + err = gqlerrors.FormatError(r) } // send panic upstream if _, ok := returnType.(*NonNull); ok { - panic(FormatError(err)) + panic(gqlerrors.FormatError(err)) } - eCtx.Errors = append(eCtx.Errors, FormatError(err)) + eCtx.Errors = append(eCtx.Errors, gqlerrors.FormatError(err)) return result, resultState } return result, resultState @@ -523,7 +525,7 @@ func resolveField(eCtx *ExecutionContext, parentType *Object, source interface{} return completed, resultState } -func completeValueCatchingError(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstField, info ResolveInfo, result interface{}) (completed interface{}) { +func completeValueCatchingError(eCtx *ExecutionContext, returnType Type, fieldASTs []*ast.Field, info ResolveInfo, result interface{}) (completed interface{}) { // catch panic defer func() interface{} { if r := recover(); r != nil { @@ -531,7 +533,7 @@ func completeValueCatchingError(eCtx *ExecutionContext, returnType Type, fieldAS if _, ok := returnType.(*NonNull); ok { panic(r) } - if err, ok := r.(FormattedError); ok { + if err, ok := r.(gqlerrors.FormattedError); ok { eCtx.Errors = append(eCtx.Errors, err) } return completed @@ -549,13 +551,13 @@ func completeValueCatchingError(eCtx *ExecutionContext, returnType Type, fieldAS if propertyFn, ok := completed.(func() interface{}); ok { return propertyFn() } - err := NewFormattedError("Error resolving func. Expected `func() interface{}` signature") - panic(FormatError(err)) + err := gqlerrors.NewFormattedError("Error resolving func. Expected `func() interface{}` signature") + panic(gqlerrors.FormatError(err)) } return completed } -func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstField, info ResolveInfo, result interface{}) interface{} { +func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*ast.Field, info ResolveInfo, result interface{}) interface{} { // TODO: explore resolving go-routines in completeValue @@ -564,8 +566,8 @@ func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstFiel if propertyFn, ok := result.(func() interface{}); ok { return propertyFn() } - err := NewFormattedError("Error resolving func. Expected `func() interface{}` signature") - panic(FormatError(err)) + err := gqlerrors.NewFormattedError("Error resolving func. Expected `func() interface{}` signature") + panic(gqlerrors.FormatError(err)) } if returnType, ok := returnType.(*NonNull); ok { @@ -575,7 +577,7 @@ func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstFiel fmt.Sprintf("Cannot return null for non-nullable field %v.%v.", info.ParentType, info.FieldName), FieldASTsToNodeASTs(fieldASTs), ) - panic(FormatError(err)) + panic(gqlerrors.FormatError(err)) } return completed } @@ -593,7 +595,7 @@ func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstFiel "User Error: expected iterable, but did not find one.", ) if err != nil { - panic(FormatError(err)) + panic(gqlerrors.FormatError(err)) } itemType := returnType.OfType @@ -611,7 +613,7 @@ func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstFiel if returnType, ok := returnType.(*Scalar); ok { err := invariant(returnType.Serialize != nil, "Missing serialize method on type") if err != nil { - panic(FormatError(err)) + panic(gqlerrors.FormatError(err)) } serializedResult := returnType.Serialize(result) if isNullish(serializedResult) { @@ -622,7 +624,7 @@ func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstFiel if returnType, ok := returnType.(*Enum); ok { err := invariant(returnType.Serialize != nil, "Missing serialize method on type") if err != nil { - panic(FormatError(err)) + panic(gqlerrors.FormatError(err)) } serializedResult := returnType.Serialize(result) if isNullish(serializedResult) { @@ -631,7 +633,7 @@ func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstFiel return serializedResult } - // AstField type must be Object, Interface or Union and expect sub-selections. + // ast.Field type must be Object, Interface or Union and expect sub-selections. var objectType *Object switch returnType := returnType.(type) { case *Object: @@ -639,7 +641,7 @@ func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstFiel case Abstract: objectType = returnType.GetObjectType(result, info) if objectType != nil && !returnType.IsPossibleType(objectType) { - panic(NewFormattedError( + panic(gqlerrors.NewFormattedError( fmt.Sprintf(`Runtime Object type "%v" is not a possible type `+ `for "%v".`, objectType, returnType), )) @@ -653,13 +655,13 @@ func completeValue(eCtx *ExecutionContext, returnType Type, fieldASTs []*AstFiel // current result. If isTypeOf returns false, then raise an error rather // than continuing execution. if objectType.IsTypeOf != nil && !objectType.IsTypeOf(result, info) { - panic(NewFormattedError( + panic(gqlerrors.NewFormattedError( fmt.Sprintf(`Expected value of type "%v" but got: %T.`, objectType, result), )) } // Collect sub-fields to execute to complete this value. - subFieldASTs := map[string][]*AstField{} + subFieldASTs := map[string][]*ast.Field{} visitedFragmentNames := map[string]bool{} for _, fieldAST := range fieldASTs { if fieldAST == nil { diff --git a/executor_test.go b/executor_test.go index ccc482a7..7c8e5ba0 100644 --- a/executor_test.go +++ b/executor_test.go @@ -5,6 +5,9 @@ import ( "fmt" "reflect" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/location" ) func TestExecutesArbitraryCode(t *testing.T) { @@ -410,11 +413,11 @@ func TestNullsOutErrorSubtrees(t *testing.T) { "sync": "sync", "syncError": nil, } - expectedErrors := []FormattedError{ - FormattedError{ + expectedErrors := []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Error getting syncError", - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 3, Column: 7, }, }, @@ -564,10 +567,10 @@ func TestThrowsIfNoOperationIsProvidedWithMultipleOperations(t *testing.T) { "a": "b", } - expectedErrors := []FormattedError{ - FormattedError{ + expectedErrors := []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Must provide operation name if query contains multiple operations.", - Locations: []SourceLocation{}, + Locations: []location.SourceLocation{}, }, } @@ -995,10 +998,10 @@ func TestFailsWhenAnIsTypeOfCheckIsNotMet(t *testing.T) { nil, }, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Expected value of type "SpecialType" but got: graphql.testNotSpecialType.`, - Locations: []SourceLocation{}, + Locations: []location.SourceLocation{}, }, }, } @@ -1064,10 +1067,10 @@ func TestFailsToExecuteQueryContainingATypeDefinition(t *testing.T) { ` expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "GraphQL cannot execute a request containing a ObjectDefinition", - Locations: []SourceLocation{}, + Locations: []location.SourceLocation{}, }, }, } diff --git a/error.go b/gqlerrors/error.go similarity index 65% rename from error.go rename to gqlerrors/error.go index 47f2e0cf..a6f59699 100644 --- a/error.go +++ b/gqlerrors/error.go @@ -1,16 +1,20 @@ -package graphql +package gqlerrors import ( "fmt" + + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/language/source" ) type Error struct { Message string Stack string - Nodes []Node - Source *Source + Nodes []ast.Node + Source *source.Source Positions []int - Locations []SourceLocation + Locations []location.SourceLocation } // implements Golang's built-in `error` interface @@ -18,7 +22,7 @@ func (g Error) Error() string { return fmt.Sprintf("%v", g.Message) } -func NewError(message string, nodes []Node, stack string, source *Source, positions []int) *Error { +func NewError(message string, nodes []ast.Node, stack string, source *source.Source, positions []int) *Error { if stack == "" && message != "" { stack = message } @@ -39,9 +43,9 @@ func NewError(message string, nodes []Node, stack string, source *Source, positi positions = append(positions, node.GetLoc().Start) } } - locations := []SourceLocation{} + locations := []location.SourceLocation{} for _, pos := range positions { - loc := GetLocation(source, pos) + loc := location.GetLocation(source, pos) locations = append(locations, loc) } return &Error{ diff --git a/formatted.go b/gqlerrors/formatted.go similarity index 84% rename from formatted.go rename to gqlerrors/formatted.go index 25b3697c..aaf054c8 100644 --- a/formatted.go +++ b/gqlerrors/formatted.go @@ -1,12 +1,14 @@ -package graphql +package gqlerrors import ( "errors" + + "github.com/chris-ramon/graphql/language/location" ) type FormattedError struct { Message string - Locations []SourceLocation + Locations []location.SourceLocation } func (g FormattedError) Error() string { @@ -35,7 +37,7 @@ func FormatError(err error) FormattedError { default: return FormattedError{ Message: err.Error(), - Locations: []SourceLocation{}, + Locations: []location.SourceLocation{}, } } } diff --git a/gqlerrors/located.go b/gqlerrors/located.go new file mode 100644 index 00000000..87029238 --- /dev/null +++ b/gqlerrors/located.go @@ -0,0 +1,31 @@ +package gqlerrors + +import ( + "github.com/chris-ramon/graphql/language/ast" +) + +func NewLocatedError(err interface{}, nodes []ast.Node) *Error { + message := "An unknown error occurred." + if err, ok := err.(error); ok { + message = err.Error() + } + if err, ok := err.(string); ok { + message = err + } + stack := message + return NewError( + message, + nodes, + stack, + nil, + []int{}, + ) +} + +func FieldASTsToNodeASTs(fieldASTs []*ast.Field) []ast.Node { + nodes := []ast.Node{} + for _, fieldAST := range fieldASTs { + nodes = append(nodes, fieldAST) + } + return nodes +} diff --git a/sortutil.go b/gqlerrors/sortutil.go similarity index 97% rename from sortutil.go rename to gqlerrors/sortutil.go index 2c237c0f..342a93da 100644 --- a/sortutil.go +++ b/gqlerrors/sortutil.go @@ -1,4 +1,4 @@ -package graphql +package gqlerrors import "bytes" diff --git a/syntax.go b/gqlerrors/syntax.go similarity index 71% rename from syntax.go rename to gqlerrors/syntax.go index 0b9f2baa..17a283a8 100644 --- a/syntax.go +++ b/gqlerrors/syntax.go @@ -1,22 +1,26 @@ -package graphql +package gqlerrors import ( "fmt" "regexp" + + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/language/source" ) -func NewSyntaxError(s *Source, position int, description string) *Error { - l := GetLocation(s, position) +func NewSyntaxError(s *source.Source, position int, description string) *Error { + l := location.GetLocation(s, position) return NewError( fmt.Sprintf("Syntax Error %s (%d:%d) %s\n\n%s", s.Name, l.Line, l.Column, description, highlightSourceAtLocation(s, l)), - []Node{}, + []ast.Node{}, "", s, []int{position}, ) } -func highlightSourceAtLocation(s *Source, l SourceLocation) string { +func highlightSourceAtLocation(s *source.Source, l location.SourceLocation) string { line := l.Line prevLineNum := fmt.Sprintf("%d", (line - 1)) lineNum := fmt.Sprintf("%d", line) diff --git a/graphql.go b/graphql.go index 4be0be75..7c712e8a 100644 --- a/graphql.go +++ b/graphql.go @@ -1,5 +1,10 @@ package graphql +import ( + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/source" +) + type Params struct { Schema Schema RequestString string @@ -9,14 +14,14 @@ type Params struct { } func Graphql(p Params, resultChannel chan *Result) { - source := NewSource(&Source{ + source := source.NewSource(&source.Source{ Body: p.RequestString, Name: "GraphQL request", }) AST, err := Parse(ParseParams{Source: source}) if err != nil { result := Result{ - Errors: FormatErrors(err), + Errors: gqlerrors.FormatErrors(err), } resultChannel <- &result return diff --git a/introspection.go b/introspection.go index 807da787..27286741 100644 --- a/introspection.go +++ b/introspection.go @@ -3,6 +3,9 @@ package graphql import ( "fmt" "reflect" + + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/printer" ) const ( @@ -140,14 +143,14 @@ func init() { return nil } astVal := astFromValue(inputVal.DefaultValue, inputVal) - return Print(astVal) + return printer.Print(astVal) } if inputVal, ok := p.Source.(*InputObjectField); ok { if inputVal.DefaultValue == nil { return nil } astVal := astFromValue(inputVal.DefaultValue, inputVal) - return Print(astVal) + return printer.Print(astVal) } return nil }, @@ -470,7 +473,7 @@ mutation operations.`, * | Number | Int / Float | * */ -func astFromValue(value interface{}, ttype Type) Value { +func astFromValue(value interface{}, ttype Type) ast.Value { if ttype, ok := ttype.(*NonNull); ok { // Note: we're not checking that the result is non-null. @@ -497,7 +500,7 @@ func astFromValue(value interface{}, ttype Type) Value { if ttype, ok := ttype.(*List); ok { if valueVal.Type().Kind() == reflect.Slice { itemType := ttype.OfType - values := []Value{} + values := []ast.Value{} for i := 0; i < valueVal.Len(); i++ { item := valueVal.Index(i).Interface() itemAST := astFromValue(item, itemType) @@ -505,7 +508,7 @@ func astFromValue(value interface{}, ttype Type) Value { values = append(values, itemAST) } } - return NewAstListValue(&AstListValue{ + return ast.NewListValue(&ast.ListValue{ Values: values, }) } else { @@ -522,44 +525,44 @@ func astFromValue(value interface{}, ttype Type) Value { } if value, ok := value.(bool); ok { - return NewAstBooleanValue(&AstBooleanValue{ + return ast.NewBooleanValue(&ast.BooleanValue{ Value: value, }) } if value, ok := value.(int); ok { if ttype == Float { - return NewAstIntValue(&AstIntValue{ + return ast.NewIntValue(&ast.IntValue{ Value: fmt.Sprintf("%v.0", value), }) } - return NewAstIntValue(&AstIntValue{ + return ast.NewIntValue(&ast.IntValue{ Value: fmt.Sprintf("%v", value), }) } if value, ok := value.(float32); ok { - return NewAstFloatValue(&AstFloatValue{ + return ast.NewFloatValue(&ast.FloatValue{ Value: fmt.Sprintf("%v", value), }) } if value, ok := value.(float64); ok { - return NewAstFloatValue(&AstFloatValue{ + return ast.NewFloatValue(&ast.FloatValue{ Value: fmt.Sprintf("%v", value), }) } if value, ok := value.(string); ok { if _, ok := ttype.(*Enum); ok { - return NewAstEnumValue(&AstEnumValue{ + return ast.NewEnumValue(&ast.EnumValue{ Value: fmt.Sprintf("%v", value), }) } - return NewAstStringValue(&AstStringValue{ + return ast.NewStringValue(&ast.StringValue{ Value: fmt.Sprintf("%v", value), }) } // fallback, treat as string - return NewAstStringValue(&AstStringValue{ + return ast.NewStringValue(&ast.StringValue{ Value: fmt.Sprintf("%v", value), }) } diff --git a/introspection_test.go b/introspection_test.go index 83670e48..86f58224 100644 --- a/introspection_test.go +++ b/introspection_test.go @@ -3,6 +3,9 @@ package graphql import ( "reflect" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/location" ) func g(t *testing.T, p Params) *Result { @@ -1208,12 +1211,12 @@ func TestIntrospection_FailsAsExpectedOnThe__TypeRootFieldWithoutAnArg(t *testin } ` expected := &Result{ - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Field "__type" argument "name" of type "String!" ` + `is required but not provided.`, - Locations: []SourceLocation{ - SourceLocation{Line: 3, Column: 9}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 3, Column: 9}, }, }, }, diff --git a/language/ast/arguments.go b/language/ast/arguments.go new file mode 100644 index 00000000..93cc7b60 --- /dev/null +++ b/language/ast/arguments.go @@ -0,0 +1,33 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/kinds" +) + +// Argument implements Node +type Argument struct { + Kind string + Loc *Location + Name *Name + Value Value +} + +func NewArgument(arg *Argument) *Argument { + if arg == nil { + arg = &Argument{} + } + return &Argument{ + Kind: kinds.Argument, + Loc: arg.Loc, + Name: arg.Name, + Value: arg.Value, + } +} + +func (arg *Argument) GetKind() string { + return arg.Kind +} + +func (arg *Argument) GetLoc() *Location { + return arg.Loc +} diff --git a/language/ast/definitions.go b/language/ast/definitions.go new file mode 100644 index 00000000..38155365 --- /dev/null +++ b/language/ast/definitions.go @@ -0,0 +1,153 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/kinds" +) + +type Definition interface { + // TODO: determine the minimal set of interface for `Definition` + GetOperation() string + GetVariableDefinitions() []*VariableDefinition + GetSelectionSet() *SelectionSet +} + +// Ensure that all definition types implements Definition interface +var _ Definition = (*OperationDefinition)(nil) +var _ Definition = (*FragmentDefinition)(nil) +var _ Definition = (Definition)(nil) + +// OperationDefinition implements Node, Definition +type OperationDefinition struct { + Kind string + Loc *Location + Operation string + Name *Name + VariableDefinitions []*VariableDefinition + Directives []*Directive + SelectionSet *SelectionSet +} + +func NewOperationDefinition(op *OperationDefinition) *OperationDefinition { + if op == nil { + op = &OperationDefinition{} + } + return &OperationDefinition{ + Kind: kinds.OperationDefinition, + Loc: op.Loc, + Operation: op.Operation, + Name: op.Name, + VariableDefinitions: op.VariableDefinitions, + Directives: op.Directives, + SelectionSet: op.SelectionSet, + } +} + +func (op *OperationDefinition) GetKind() string { + return op.Kind +} + +func (op *OperationDefinition) GetLoc() *Location { + return op.Loc +} + +func (op *OperationDefinition) GetOperation() string { + return op.Operation +} + +func (op *OperationDefinition) GetName() *Name { + return op.Name +} + +func (op *OperationDefinition) GetVariableDefinitions() []*VariableDefinition { + return op.VariableDefinitions +} + +func (op *OperationDefinition) GetDirectives() []*Directive { + return op.Directives +} + +func (op *OperationDefinition) GetSelectionSet() *SelectionSet { + return op.SelectionSet +} + +// FragmentDefinition implements Node, Definition +type FragmentDefinition struct { + Kind string + Loc *Location + Operation string + Name *Name + VariableDefinitions []*VariableDefinition + TypeCondition *Named + Directives []*Directive + SelectionSet *SelectionSet +} + +func NewFragmentDefinition(fd *FragmentDefinition) *FragmentDefinition { + if fd == nil { + fd = &FragmentDefinition{} + } + return &FragmentDefinition{ + Kind: kinds.FragmentDefinition, + Loc: fd.Loc, + Operation: fd.Operation, + Name: fd.Name, + VariableDefinitions: fd.VariableDefinitions, + TypeCondition: fd.TypeCondition, + Directives: fd.Directives, + SelectionSet: fd.SelectionSet, + } +} + +func (fd *FragmentDefinition) GetKind() string { + return fd.Kind +} + +func (fd *FragmentDefinition) GetLoc() *Location { + return fd.Loc +} + +func (fd *FragmentDefinition) GetOperation() string { + return fd.Operation +} + +func (fd *FragmentDefinition) GetName() *Name { + return fd.Name +} + +func (fd *FragmentDefinition) GetVariableDefinitions() []*VariableDefinition { + return fd.VariableDefinitions +} + +func (fd *FragmentDefinition) GetSelectionSet() *SelectionSet { + return fd.SelectionSet +} + +// VariableDefinition implements Node +type VariableDefinition struct { + Kind string + Loc *Location + Variable *Variable + Type Type + DefaultValue Value +} + +func NewVariableDefinition(vd *VariableDefinition) *VariableDefinition { + if vd == nil { + vd = &VariableDefinition{} + } + return &VariableDefinition{ + Kind: kinds.VariableDefinition, + Loc: vd.Loc, + Variable: vd.Variable, + Type: vd.Type, + DefaultValue: vd.DefaultValue, + } +} + +func (vd *VariableDefinition) GetKind() string { + return vd.Kind +} + +func (vd *VariableDefinition) GetLoc() *Location { + return vd.Loc +} diff --git a/language/ast/directives.go b/language/ast/directives.go new file mode 100644 index 00000000..7dd49269 --- /dev/null +++ b/language/ast/directives.go @@ -0,0 +1,33 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/kinds" +) + +// Directive implements Node +type Directive struct { + Kind string + Loc *Location + Name *Name + Arguments []*Argument +} + +func NewDirective(dir *Directive) *Directive { + if dir == nil { + dir = &Directive{} + } + return &Directive{ + Kind: kinds.Directive, + Loc: dir.Loc, + Name: dir.Name, + Arguments: dir.Arguments, + } +} + +func (dir *Directive) GetKind() string { + return dir.Kind +} + +func (dir *Directive) GetLoc() *Location { + return dir.Loc +} diff --git a/language/ast/document.go b/language/ast/document.go new file mode 100644 index 00000000..34385da9 --- /dev/null +++ b/language/ast/document.go @@ -0,0 +1,31 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/kinds" +) + +// Document implements Node +type Document struct { + Kind string + Loc *Location + Definitions []Node +} + +func NewDocument(d *Document) *Document { + if d == nil { + d = &Document{} + } + return &Document{ + Kind: kinds.Document, + Loc: d.Loc, + Definitions: d.Definitions, + } +} + +func (node *Document) GetKind() string { + return node.Kind +} + +func (node *Document) GetLoc() *Location { + return node.Loc +} diff --git a/language/ast/location.go b/language/ast/location.go new file mode 100644 index 00000000..6f60120c --- /dev/null +++ b/language/ast/location.go @@ -0,0 +1,22 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/source" +) + +type Location struct { + Start int + End int + Source *source.Source +} + +func NewLocation(loc *Location) *Location { + if loc == nil { + loc = &Location{} + } + return &Location{ + Start: loc.Start, + End: loc.End, + Source: loc.Source, + } +} diff --git a/language/ast/name.go b/language/ast/name.go new file mode 100644 index 00000000..645f1bfc --- /dev/null +++ b/language/ast/name.go @@ -0,0 +1,31 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/kinds" +) + +// Name implements Node +type Name struct { + Kind string + Loc *Location + Value string +} + +func NewName(node *Name) *Name { + if node == nil { + node = &Name{} + } + return &Name{ + Kind: kinds.Name, + Value: node.Value, + Loc: node.Loc, + } +} + +func (node *Name) GetKind() string { + return node.Kind +} + +func (node *Name) GetLoc() *Location { + return node.Loc +} diff --git a/language/ast/node.go b/language/ast/node.go new file mode 100644 index 00000000..f35eb21d --- /dev/null +++ b/language/ast/node.go @@ -0,0 +1,45 @@ +package ast + +type Node interface { + GetKind() string + GetLoc() *Location +} + +// The list of all possible AST node graphql. +// Ensure that all node types implements Node interface +var _ Node = (*Name)(nil) +var _ Node = (*Document)(nil) +var _ Node = (*OperationDefinition)(nil) +var _ Node = (*VariableDefinition)(nil) +var _ Node = (*Variable)(nil) +var _ Node = (*SelectionSet)(nil) +var _ Node = (*Field)(nil) +var _ Node = (*Argument)(nil) +var _ Node = (*FragmentSpread)(nil) +var _ Node = (*InlineFragment)(nil) +var _ Node = (*FragmentDefinition)(nil) +var _ Node = (*IntValue)(nil) +var _ Node = (*FloatValue)(nil) +var _ Node = (*StringValue)(nil) +var _ Node = (*BooleanValue)(nil) +var _ Node = (*EnumValue)(nil) +var _ Node = (*ListValue)(nil) +var _ Node = (*ObjectValue)(nil) +var _ Node = (*ObjectField)(nil) +var _ Node = (*Directive)(nil) +var _ Node = (*List)(nil) +var _ Node = (*NonNull)(nil) +var _ Node = (*ObjectDefinition)(nil) +var _ Node = (*FieldDefinition)(nil) +var _ Node = (*InputValueDefinition)(nil) +var _ Node = (*InterfaceDefinition)(nil) +var _ Node = (*UnionDefinition)(nil) +var _ Node = (*ScalarDefinition)(nil) +var _ Node = (*EnumDefinition)(nil) +var _ Node = (*EnumValueDefinition)(nil) +var _ Node = (*InputObjectDefinition)(nil) +var _ Node = (*TypeExtensionDefinition)(nil) + +// TODO: File issue in `graphql-js` where Named is not +// defined as a Node. This might be a mistake in `graphql-js`? +var _ Node = (*Named)(nil) diff --git a/language/ast/selections.go b/language/ast/selections.go new file mode 100644 index 00000000..0fe5a4fc --- /dev/null +++ b/language/ast/selections.go @@ -0,0 +1,131 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/kinds" +) + +type Selection interface { +} + +// Ensure that all definition types implements Selection interface +var _ Selection = (*Field)(nil) +var _ Selection = (*FragmentSpread)(nil) +var _ Selection = (*InlineFragment)(nil) + +// Field implements Node, Selection +type Field struct { + Kind string + Loc *Location + Alias *Name + Name *Name + Arguments []*Argument + Directives []*Directive + SelectionSet *SelectionSet +} + +func NewField(f *Field) *Field { + if f == nil { + f = &Field{} + } + return &Field{ + Kind: kinds.Field, + Loc: f.Loc, + Alias: f.Alias, + Name: f.Name, + Arguments: f.Arguments, + Directives: f.Directives, + SelectionSet: f.SelectionSet, + } +} + +func (f *Field) GetKind() string { + return f.Kind +} + +func (f *Field) GetLoc() *Location { + return f.Loc +} + +// FragmentSpread implements Node, Selection +type FragmentSpread struct { + Kind string + Loc *Location + Name *Name + Directives []*Directive +} + +func NewFragmentSpread(fs *FragmentSpread) *FragmentSpread { + if fs == nil { + fs = &FragmentSpread{} + } + return &FragmentSpread{ + Kind: kinds.FragmentSpread, + Loc: fs.Loc, + Name: fs.Name, + Directives: fs.Directives, + } +} + +func (fs *FragmentSpread) GetKind() string { + return fs.Kind +} + +func (fs *FragmentSpread) GetLoc() *Location { + return fs.Loc +} + +// InlineFragment implements Node, Selection +type InlineFragment struct { + Kind string + Loc *Location + TypeCondition *Named + Directives []*Directive + SelectionSet *SelectionSet +} + +func NewInlineFragment(f *InlineFragment) *InlineFragment { + if f == nil { + f = &InlineFragment{} + } + return &InlineFragment{ + Kind: kinds.InlineFragment, + Loc: f.Loc, + TypeCondition: f.TypeCondition, + Directives: f.Directives, + SelectionSet: f.SelectionSet, + } +} + +func (f *InlineFragment) GetKind() string { + return f.Kind +} + +func (f *InlineFragment) GetLoc() *Location { + return f.Loc +} + +// SelectionSet implements Node +type SelectionSet struct { + Kind string + Loc *Location + Selections []Selection +} + +func NewSelectionSet(ss *SelectionSet) *SelectionSet { + if ss == nil { + ss = &SelectionSet{} + } + return &SelectionSet{ + Kind: kinds.SelectionSet, + Loc: ss.Loc, + Selections: ss.Selections, + } +} + +func (ss *SelectionSet) GetKind() string { + return ss.Kind +} + +func (ss *SelectionSet) GetLoc() *Location { + return ss.Loc +} diff --git a/language/ast/type_definitions.go b/language/ast/type_definitions.go new file mode 100644 index 00000000..18b07503 --- /dev/null +++ b/language/ast/type_definitions.go @@ -0,0 +1,402 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/kinds" +) + +// Ensure that all typeDefinition types implements Definition interface +var _ Definition = (*ObjectDefinition)(nil) +var _ Definition = (*InterfaceDefinition)(nil) +var _ Definition = (*UnionDefinition)(nil) +var _ Definition = (*ScalarDefinition)(nil) +var _ Definition = (*EnumDefinition)(nil) +var _ Definition = (*InputObjectDefinition)(nil) +var _ Definition = (*TypeExtensionDefinition)(nil) + +// ObjectDefinition implements Node, Definition +type ObjectDefinition struct { + Kind string + Loc *Location + Name *Name + Interfaces []*Named + Fields []*FieldDefinition +} + +func NewObjectDefinition(def *ObjectDefinition) *ObjectDefinition { + if def == nil { + def = &ObjectDefinition{} + } + return &ObjectDefinition{ + Kind: kinds.ObjectDefinition, + Loc: def.Loc, + Name: def.Name, + Interfaces: def.Interfaces, + Fields: def.Fields, + } +} + +func (def *ObjectDefinition) GetKind() string { + return def.Kind +} + +func (def *ObjectDefinition) GetLoc() *Location { + return def.Loc +} + +func (def *ObjectDefinition) GetName() *Name { + return def.Name +} + +func (def *ObjectDefinition) GetVariableDefinitions() []*VariableDefinition { + return []*VariableDefinition{} +} + +func (def *ObjectDefinition) GetSelectionSet() *SelectionSet { + return &SelectionSet{} +} + +func (def *ObjectDefinition) GetOperation() string { + return "" +} + +// FieldDefinition implements Node +type FieldDefinition struct { + Kind string + Loc *Location + Name *Name + Arguments []*InputValueDefinition + Type Type +} + +func NewFieldDefinition(def *FieldDefinition) *FieldDefinition { + if def == nil { + def = &FieldDefinition{} + } + return &FieldDefinition{ + Kind: kinds.FieldDefinition, + Loc: def.Loc, + Name: def.Name, + Arguments: def.Arguments, + Type: def.Type, + } +} + +func (def *FieldDefinition) GetKind() string { + return def.Kind +} + +func (def *FieldDefinition) GetLoc() *Location { + return def.Loc +} + +// InputValueDefinition implements Node +type InputValueDefinition struct { + Kind string + Loc *Location + Name *Name + Type Type + DefaultValue Value +} + +func NewInputValueDefinition(def *InputValueDefinition) *InputValueDefinition { + if def == nil { + def = &InputValueDefinition{} + } + return &InputValueDefinition{ + Kind: kinds.InputValueDefinition, + Loc: def.Loc, + Name: def.Name, + Type: def.Type, + DefaultValue: def.DefaultValue, + } +} + +func (def *InputValueDefinition) GetKind() string { + return def.Kind +} + +func (def *InputValueDefinition) GetLoc() *Location { + return def.Loc +} + +// InterfaceDefinition implements Node, Definition +type InterfaceDefinition struct { + Kind string + Loc *Location + Name *Name + Fields []*FieldDefinition +} + +func NewInterfaceDefinition(def *InterfaceDefinition) *InterfaceDefinition { + if def == nil { + def = &InterfaceDefinition{} + } + return &InterfaceDefinition{ + Kind: kinds.InterfaceDefinition, + Loc: def.Loc, + Name: def.Name, + Fields: def.Fields, + } +} + +func (def *InterfaceDefinition) GetKind() string { + return def.Kind +} + +func (def *InterfaceDefinition) GetLoc() *Location { + return def.Loc +} + +func (def *InterfaceDefinition) GetName() *Name { + return def.Name +} + +func (def *InterfaceDefinition) GetVariableDefinitions() []*VariableDefinition { + return []*VariableDefinition{} +} + +func (def *InterfaceDefinition) GetSelectionSet() *SelectionSet { + return &SelectionSet{} +} + +func (def *InterfaceDefinition) GetOperation() string { + return "" +} + +// UnionDefinition implements Node, Definition +type UnionDefinition struct { + Kind string + Loc *Location + Name *Name + Types []*Named +} + +func NewUnionDefinition(def *UnionDefinition) *UnionDefinition { + if def == nil { + def = &UnionDefinition{} + } + return &UnionDefinition{ + Kind: kinds.UnionDefinition, + Loc: def.Loc, + Name: def.Name, + Types: def.Types, + } +} + +func (def *UnionDefinition) GetKind() string { + return def.Kind +} + +func (def *UnionDefinition) GetLoc() *Location { + return def.Loc +} + +func (def *UnionDefinition) GetName() *Name { + return def.Name +} + +func (def *UnionDefinition) GetVariableDefinitions() []*VariableDefinition { + return []*VariableDefinition{} +} + +func (def *UnionDefinition) GetSelectionSet() *SelectionSet { + return &SelectionSet{} +} + +func (def *UnionDefinition) GetOperation() string { + return "" +} + +// ScalarDefinition implements Node, Definition +type ScalarDefinition struct { + Kind string + Loc *Location + Name *Name +} + +func NewScalarDefinition(def *ScalarDefinition) *ScalarDefinition { + if def == nil { + def = &ScalarDefinition{} + } + return &ScalarDefinition{ + Kind: kinds.ScalarDefinition, + Loc: def.Loc, + Name: def.Name, + } +} + +func (def *ScalarDefinition) GetKind() string { + return def.Kind +} + +func (def *ScalarDefinition) GetLoc() *Location { + return def.Loc +} + +func (def *ScalarDefinition) GetName() *Name { + return def.Name +} + +func (def *ScalarDefinition) GetVariableDefinitions() []*VariableDefinition { + return []*VariableDefinition{} +} + +func (def *ScalarDefinition) GetSelectionSet() *SelectionSet { + return &SelectionSet{} +} + +func (def *ScalarDefinition) GetOperation() string { + return "" +} + +// EnumDefinition implements Node, Definition +type EnumDefinition struct { + Kind string + Loc *Location + Name *Name + Values []*EnumValueDefinition +} + +func NewEnumDefinition(def *EnumDefinition) *EnumDefinition { + if def == nil { + def = &EnumDefinition{} + } + return &EnumDefinition{ + Kind: kinds.EnumDefinition, + Loc: def.Loc, + Name: def.Name, + Values: def.Values, + } +} + +func (def *EnumDefinition) GetKind() string { + return def.Kind +} + +func (def *EnumDefinition) GetLoc() *Location { + return def.Loc +} + +func (def *EnumDefinition) GetName() *Name { + return def.Name +} + +func (def *EnumDefinition) GetVariableDefinitions() []*VariableDefinition { + return []*VariableDefinition{} +} + +func (def *EnumDefinition) GetSelectionSet() *SelectionSet { + return &SelectionSet{} +} + +func (def *EnumDefinition) GetOperation() string { + return "" +} + +// EnumValueDefinition implements Node, Definition +type EnumValueDefinition struct { + Kind string + Loc *Location + Name *Name +} + +func NewEnumValueDefinition(def *EnumValueDefinition) *EnumValueDefinition { + if def == nil { + def = &EnumValueDefinition{} + } + return &EnumValueDefinition{ + Kind: kinds.EnumValueDefinition, + Loc: def.Loc, + Name: def.Name, + } +} + +func (def *EnumValueDefinition) GetKind() string { + return def.Kind +} + +func (def *EnumValueDefinition) GetLoc() *Location { + return def.Loc +} + +// InputObjectDefinition implements Node, Definition +type InputObjectDefinition struct { + Kind string + Loc *Location + Name *Name + Fields []*InputValueDefinition +} + +func NewInputObjectDefinition(def *InputObjectDefinition) *InputObjectDefinition { + if def == nil { + def = &InputObjectDefinition{} + } + return &InputObjectDefinition{ + Kind: kinds.InputObjectDefinition, + Loc: def.Loc, + Name: def.Name, + Fields: def.Fields, + } +} + +func (def *InputObjectDefinition) GetKind() string { + return def.Kind +} + +func (def *InputObjectDefinition) GetLoc() *Location { + return def.Loc +} + +func (def *InputObjectDefinition) GetName() *Name { + return def.Name +} + +func (def *InputObjectDefinition) GetVariableDefinitions() []*VariableDefinition { + return []*VariableDefinition{} +} + +func (def *InputObjectDefinition) GetSelectionSet() *SelectionSet { + return &SelectionSet{} +} + +func (def *InputObjectDefinition) GetOperation() string { + return "" +} + +// TypeExtensionDefinition implements Node, Definition +type TypeExtensionDefinition struct { + Kind string + Loc *Location + Definition *ObjectDefinition +} + +func NewTypeExtensionDefinition(def *TypeExtensionDefinition) *TypeExtensionDefinition { + if def == nil { + def = &TypeExtensionDefinition{} + } + return &TypeExtensionDefinition{ + Kind: kinds.TypeExtensionDefinition, + Loc: def.Loc, + Definition: def.Definition, + } +} + +func (def *TypeExtensionDefinition) GetKind() string { + return def.Kind +} + +func (def *TypeExtensionDefinition) GetLoc() *Location { + return def.Loc +} + +func (def *TypeExtensionDefinition) GetVariableDefinitions() []*VariableDefinition { + return []*VariableDefinition{} +} + +func (def *TypeExtensionDefinition) GetSelectionSet() *SelectionSet { + return &SelectionSet{} +} + +func (def *TypeExtensionDefinition) GetOperation() string { + return "" +} diff --git a/language/ast/types.go b/language/ast/types.go new file mode 100644 index 00000000..146217c3 --- /dev/null +++ b/language/ast/types.go @@ -0,0 +1,106 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/kinds" +) + +type Type interface { + GetKind() string + GetLoc() *Location + String() string +} + +// Ensure that all value types implements Value interface +var _ Type = (*Named)(nil) +var _ Type = (*List)(nil) +var _ Type = (*NonNull)(nil) + +// Named implements Node, Type +type Named struct { + Kind string + Loc *Location + Name *Name +} + +func NewNamed(t *Named) *Named { + if t == nil { + t = &Named{} + } + return &Named{ + Kind: kinds.Named, + Loc: t.Loc, + Name: t.Name, + } +} + +func (t *Named) GetKind() string { + return t.Kind +} + +func (t *Named) GetLoc() *Location { + return t.Loc +} + +func (t *Named) String() string { + return t.GetKind() +} + +// List implements Node, Type +type List struct { + Kind string + Loc *Location + Type Type +} + +func NewList(t *List) *List { + if t == nil { + t = &List{} + } + return &List{ + Kind: kinds.List, + Loc: t.Loc, + Type: t.Type, + } +} + +func (t *List) GetKind() string { + return t.Kind +} + +func (t *List) GetLoc() *Location { + return t.Loc +} + +func (t *List) String() string { + return t.GetKind() +} + +// NonNull implements Node, Type +type NonNull struct { + Kind string + Loc *Location + Type Type +} + +func NewNonNull(t *NonNull) *NonNull { + if t == nil { + t = &NonNull{} + } + return &NonNull{ + Kind: kinds.NonNull, + Loc: t.Loc, + Type: t.Type, + } +} + +func (t *NonNull) GetKind() string { + return t.Kind +} + +func (t *NonNull) GetLoc() *Location { + return t.Loc +} + +func (t *NonNull) String() string { + return t.GetKind() +} diff --git a/language/ast/values.go b/language/ast/values.go new file mode 100644 index 00000000..2b484a66 --- /dev/null +++ b/language/ast/values.go @@ -0,0 +1,305 @@ +package ast + +import ( + "github.com/chris-ramon/graphql/language/kinds" +) + +type Value interface { + GetValue() interface{} + GetKind() string + GetLoc() *Location +} + +// Ensure that all value types implements Value interface +var _ Value = (*Variable)(nil) +var _ Value = (*IntValue)(nil) +var _ Value = (*FloatValue)(nil) +var _ Value = (*StringValue)(nil) +var _ Value = (*BooleanValue)(nil) +var _ Value = (*EnumValue)(nil) +var _ Value = (*ListValue)(nil) +var _ Value = (*ObjectValue)(nil) + +// Variable implements Node, Value +type Variable struct { + Kind string + Loc *Location + Name *Name +} + +func NewVariable(v *Variable) *Variable { + if v == nil { + v = &Variable{} + } + return &Variable{ + Kind: kinds.Variable, + Loc: v.Loc, + Name: v.Name, + } +} + +func (v *Variable) GetKind() string { + return v.Kind +} + +func (v *Variable) GetLoc() *Location { + return v.Loc +} + +// GetValue alias to Variable.GetName() +func (v *Variable) GetValue() interface{} { + return v.GetName() +} + +func (v *Variable) GetName() interface{} { + return v.Name +} + +// IntValue implements Node, Value +type IntValue struct { + Kind string + Loc *Location + Value string +} + +func NewIntValue(v *IntValue) *IntValue { + if v == nil { + v = &IntValue{} + } + return &IntValue{ + Kind: kinds.IntValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *IntValue) GetKind() string { + return v.Kind +} + +func (v *IntValue) GetLoc() *Location { + return v.Loc +} + +func (v *IntValue) GetValue() interface{} { + return v.Value +} + +// FloatValue implements Node, Value +type FloatValue struct { + Kind string + Loc *Location + Value string +} + +func NewFloatValue(v *FloatValue) *FloatValue { + if v == nil { + v = &FloatValue{} + } + return &FloatValue{ + Kind: kinds.FloatValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *FloatValue) GetKind() string { + return v.Kind +} + +func (v *FloatValue) GetLoc() *Location { + return v.Loc +} + +func (v *FloatValue) GetValue() interface{} { + return v.Value +} + +// StringValue implements Node, Value +type StringValue struct { + Kind string + Loc *Location + Value string +} + +func NewStringValue(v *StringValue) *StringValue { + if v == nil { + v = &StringValue{} + } + return &StringValue{ + Kind: kinds.StringValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *StringValue) GetKind() string { + return v.Kind +} + +func (v *StringValue) GetLoc() *Location { + return v.Loc +} + +func (v *StringValue) GetValue() interface{} { + return v.Value +} + +// BooleanValue implements Node, Value +type BooleanValue struct { + Kind string + Loc *Location + Value bool +} + +func NewBooleanValue(v *BooleanValue) *BooleanValue { + if v == nil { + v = &BooleanValue{} + } + return &BooleanValue{ + Kind: kinds.BooleanValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *BooleanValue) GetKind() string { + return v.Kind +} + +func (v *BooleanValue) GetLoc() *Location { + return v.Loc +} + +func (v *BooleanValue) GetValue() interface{} { + return v.Value +} + +// EnumValue implements Node, Value +type EnumValue struct { + Kind string + Loc *Location + Value string +} + +func NewEnumValue(v *EnumValue) *EnumValue { + if v == nil { + v = &EnumValue{} + } + return &EnumValue{ + Kind: kinds.EnumValue, + Loc: v.Loc, + Value: v.Value, + } +} + +func (v *EnumValue) GetKind() string { + return v.Kind +} + +func (v *EnumValue) GetLoc() *Location { + return v.Loc +} + +func (v *EnumValue) GetValue() interface{} { + return v.Value +} + +// ListValue implements Node, Value +type ListValue struct { + Kind string + Loc *Location + Values []Value +} + +func NewListValue(v *ListValue) *ListValue { + if v == nil { + v = &ListValue{} + } + return &ListValue{ + Kind: kinds.ListValue, + Loc: v.Loc, + Values: v.Values, + } +} + +func (v *ListValue) GetKind() string { + return v.Kind +} + +func (v *ListValue) GetLoc() *Location { + return v.Loc +} + +// GetValue alias to ListValue.GetValues() +func (v *ListValue) GetValue() interface{} { + return v.GetValues() +} + +func (v *ListValue) GetValues() interface{} { + // TODO: verify ObjectValue.GetValue() + return v.Values +} + +// ObjectValue implements Node, Value +type ObjectValue struct { + Kind string + Loc *Location + Fields []*ObjectField +} + +func NewObjectValue(v *ObjectValue) *ObjectValue { + if v == nil { + v = &ObjectValue{} + } + return &ObjectValue{ + Kind: kinds.ObjectValue, + Loc: v.Loc, + Fields: v.Fields, + } +} + +func (v *ObjectValue) GetKind() string { + return v.Kind +} + +func (v *ObjectValue) GetLoc() *Location { + return v.Loc +} + +func (v *ObjectValue) GetValue() interface{} { + // TODO: verify ObjectValue.GetValue() + return v.Fields +} + +// ObjectField implements Node, Value +type ObjectField struct { + Kind string + Name *Name + Loc *Location + Value Value +} + +func NewObjectField(f *ObjectField) *ObjectField { + if f == nil { + f = &ObjectField{} + } + return &ObjectField{ + Kind: kinds.ObjectField, + Loc: f.Loc, + Name: f.Name, + Value: f.Value, + } +} + +func (f *ObjectField) GetKind() string { + return f.Kind +} + +func (f *ObjectField) GetLoc() *Location { + return f.Loc +} + +func (f *ObjectField) GetValue() interface{} { + return f.Value +} diff --git a/kinds/kinds.go b/language/kinds/kinds.go similarity index 100% rename from kinds/kinds.go rename to language/kinds/kinds.go diff --git a/lexer.go b/language/lexer/lexer.go similarity index 91% rename from lexer.go rename to language/lexer/lexer.go index 10004ecc..5dccefd6 100644 --- a/lexer.go +++ b/language/lexer/lexer.go @@ -1,7 +1,10 @@ -package graphql +package lexer import ( "fmt" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/source" ) const ( @@ -85,7 +88,7 @@ func (t *Token) String() string { type Lexer func(resetPosition int) (Token, error) -func Lex(s *Source) Lexer { +func Lex(s *source.Source) Lexer { var prevPosition int return func(resetPosition int) (Token, error) { if resetPosition == 0 { @@ -102,7 +105,7 @@ func Lex(s *Source) Lexer { // Reads an alphanumeric + underscore name from the source. // [_A-Za-z][_0-9A-Za-z]* -func readName(source *Source, position int) Token { +func readName(source *source.Source, position int) Token { body := source.Body bodyLength := len(body) end := position + 1 @@ -125,7 +128,7 @@ func readName(source *Source, position int) Token { // or an int depending on whether a decimal point appears. // Int: -?(0|[1-9][0-9]*) // Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? -func readNumber(s *Source, start int, firstCode rune) (Token, error) { +func readNumber(s *source.Source, start int, firstCode rune) (Token, error) { code := firstCode body := s.Body position := start @@ -139,7 +142,7 @@ func readNumber(s *Source, start int, firstCode rune) (Token, error) { code = charCodeAt(body, position) if code >= 48 && code <= 57 { description := fmt.Sprintf("Invalid number, unexpected digit after 0: \"%c\".", code) - return Token{}, NewSyntaxError(s, position, description) + return Token{}, gqlerrors.NewSyntaxError(s, position, description) } } else { p, err := readDigits(s, position, code) @@ -182,7 +185,7 @@ func readNumber(s *Source, start int, firstCode rune) (Token, error) { } // Returns the new position in the source after reading digits. -func readDigits(s *Source, start int, firstCode rune) (int, error) { +func readDigits(s *source.Source, start int, firstCode rune) (int, error) { body := s.Body position := start code := firstCode @@ -204,10 +207,10 @@ func readDigits(s *Source, start int, firstCode rune) (int, error) { } else { description = fmt.Sprintf("Invalid number, expected digit but got: EOF.") } - return position, NewSyntaxError(s, position, description) + return position, gqlerrors.NewSyntaxError(s, position, description) } -func readString(s *Source, start int) (Token, error) { +func readString(s *source.Source, start int) (Token, error) { body := s.Body position := start + 1 chunkStart := position @@ -253,13 +256,13 @@ func readString(s *Source, start int) (Token, error) { charCodeAt(body, position+4), ) if charCode < 0 { - return Token{}, NewSyntaxError(s, position, "Bad character escape sequence.") + return Token{}, gqlerrors.NewSyntaxError(s, position, "Bad character escape sequence.") } value += fmt.Sprintf("%c", charCode) position += 4 break default: - return Token{}, NewSyntaxError(s, position, "Bad character escape sequence.") + return Token{}, gqlerrors.NewSyntaxError(s, position, "Bad character escape sequence.") } position += 1 chunkStart = position @@ -270,7 +273,7 @@ func readString(s *Source, start int) (Token, error) { } } if code != 34 { - return Token{}, NewSyntaxError(s, position, "Unterminated string.") + return Token{}, gqlerrors.NewSyntaxError(s, position, "Unterminated string.") } value += body[chunkStart:position] return makeToken(TokenKind[STRING], start, position+1, value), nil @@ -307,7 +310,7 @@ func makeToken(kind int, start int, end int, value string) Token { return Token{Kind: kind, Start: start, End: end, Value: value} } -func readToken(s *Source, fromPosition int) (Token, error) { +func readToken(s *source.Source, fromPosition int) (Token, error) { body := s.Body bodyLength := len(body) position := positionAfterWhitespace(body, fromPosition) @@ -385,7 +388,7 @@ func readToken(s *Source, fromPosition int) (Token, error) { return token, nil } description := fmt.Sprintf("Unexpected character \"%c\".", code) - return Token{}, NewSyntaxError(s, position, description) + return Token{}, gqlerrors.NewSyntaxError(s, position, description) } func charCodeAt(body string, position int) rune { diff --git a/lexer_test.go b/language/lexer/lexer_test.go similarity index 97% rename from lexer_test.go rename to language/lexer/lexer_test.go index 894f268e..ac56ee73 100644 --- a/lexer_test.go +++ b/language/lexer/lexer_test.go @@ -1,8 +1,10 @@ -package graphql +package lexer import ( "reflect" "testing" + + "github.com/chris-ramon/graphql/language/source" ) type Test struct { @@ -10,8 +12,8 @@ type Test struct { Expected interface{} } -func createSource(body string) *Source { - return NewSource(&Source{Body: body}) +func createSource(body string) *source.Source { + return source.NewSource(&source.Source{Body: body}) } func TestSkipsWhiteSpace(t *testing.T) { @@ -52,7 +54,7 @@ func TestSkipsWhiteSpace(t *testing.T) { }, } for _, test := range tests { - token, err := Lex(&Source{Body: test.Body})(0) + token, err := Lex(&source.Source{Body: test.Body})(0) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -136,7 +138,7 @@ func TestLexesStrings(t *testing.T) { }, } for _, test := range tests { - token, err := Lex(&Source{Body: test.Body})(0) + token, err := Lex(&source.Source{Body: test.Body})(0) if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/location.go b/language/location/location.go similarity index 80% rename from location.go rename to language/location/location.go index 022d2d84..6ec9784d 100644 --- a/location.go +++ b/language/location/location.go @@ -1,7 +1,9 @@ -package graphql +package location import ( "regexp" + + "github.com/chris-ramon/graphql/language/source" ) type SourceLocation struct { @@ -9,7 +11,7 @@ type SourceLocation struct { Column int } -func GetLocation(s *Source, position int) SourceLocation { +func GetLocation(s *source.Source, position int) SourceLocation { body := "" if s != nil { body = s.Body diff --git a/printer.go b/language/printer/printer.go similarity index 56% rename from printer.go rename to language/printer/printer.go index 1f55e301..676bed07 100644 --- a/printer.go +++ b/language/printer/printer.go @@ -1,8 +1,11 @@ -package graphql +package printer import ( "fmt" "strings" + + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/visitor" ) func getMapValue(m map[string]interface{}, key string) interface{} { @@ -100,30 +103,30 @@ func indent(maybeString interface{}) string { return "" } -var printDocASTReducer = map[string]VisitFunc{ - "Name": func(p VisitFuncParams) (string, interface{}) { +var printDocASTReducer = map[string]visitor.VisitFunc{ + "Name": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, getMapValue(node, "Value") + return visitor.ActionUpdate, getMapValue(node, "Value") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "Variable": func(p VisitFuncParams) (string, interface{}) { + "Variable": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, "$" + getMapValueString(node, "Name") + return visitor.ActionUpdate, "$" + getMapValueString(node, "Name") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "Document": func(p VisitFuncParams) (string, interface{}) { + "Document": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: definitions := toSliceString(getMapValue(node, "Definitions")) - return ActionUpdate, join(definitions, "\n\n") + "\n" + return visitor.ActionUpdate, join(definitions, "\n\n") + "\n" } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "OperationDefinition": func(p VisitFuncParams) (string, interface{}) { + "OperationDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: op := getMapValueString(node, "Operation") @@ -143,11 +146,11 @@ var printDocASTReducer = map[string]VisitFunc{ selectionSet, }, " ") } - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "VariableDefinition": func(p VisitFuncParams) (string, interface{}) { + "VariableDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: @@ -155,22 +158,22 @@ var printDocASTReducer = map[string]VisitFunc{ ttype := getMapValueString(node, "Type") defaultValue := getMapValueString(node, "DefaultValue") - return ActionUpdate, variable + ": " + ttype + wrap(" = ", defaultValue, "") + return visitor.ActionUpdate, variable + ": " + ttype + wrap(" = ", defaultValue, "") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "SelectionSet": func(p VisitFuncParams) (string, interface{}) { + "SelectionSet": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: selections := getMapValue(node, "Selections") str := block(selections) - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "Field": func(p VisitFuncParams) (string, interface{}) { + "Field": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: @@ -188,249 +191,249 @@ var printDocASTReducer = map[string]VisitFunc{ }, " ", ) - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "Argument": func(p VisitFuncParams) (string, interface{}) { + "Argument": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") value := getMapValueString(node, "Value") - return ActionUpdate, name + ": " + value + return visitor.ActionUpdate, name + ": " + value } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "FragmentSpread": func(p VisitFuncParams) (string, interface{}) { + "FragmentSpread": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") directives := toSliceString(getMapValue(node, "Directives")) - return ActionUpdate, "..." + name + wrap(" ", join(directives, " "), "") + return visitor.ActionUpdate, "..." + name + wrap(" ", join(directives, " "), "") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "InlineFragment": func(p VisitFuncParams) (string, interface{}) { + "InlineFragment": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: typeCondition := getMapValueString(node, "TypeCondition") directives := toSliceString(getMapValue(node, "Directives")) selectionSet := getMapValueString(node, "SelectionSet") - return ActionUpdate, "... on " + typeCondition + " " + wrap("", join(directives, " "), " ") + selectionSet + return visitor.ActionUpdate, "... on " + typeCondition + " " + wrap("", join(directives, " "), " ") + selectionSet } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "FragmentDefinition": func(p VisitFuncParams) (string, interface{}) { + "FragmentDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") typeCondition := getMapValueString(node, "TypeCondition") directives := toSliceString(getMapValue(node, "Directives")) selectionSet := getMapValueString(node, "SelectionSet") - return ActionUpdate, "fragment " + name + " on " + typeCondition + " " + wrap("", join(directives, " "), " ") + selectionSet + return visitor.ActionUpdate, "fragment " + name + " on " + typeCondition + " " + wrap("", join(directives, " "), " ") + selectionSet } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "IntValue": func(p VisitFuncParams) (string, interface{}) { + "IntValue": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, getMapValueString(node, "Value") + return visitor.ActionUpdate, getMapValueString(node, "Value") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "FloatValue": func(p VisitFuncParams) (string, interface{}) { + "FloatValue": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, getMapValueString(node, "Value") + return visitor.ActionUpdate, getMapValueString(node, "Value") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "StringValue": func(p VisitFuncParams) (string, interface{}) { + "StringValue": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, `"` + getMapValueString(node, "Value") + `"` + return visitor.ActionUpdate, `"` + getMapValueString(node, "Value") + `"` } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "BooleanValue": func(p VisitFuncParams) (string, interface{}) { + "BooleanValue": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, getMapValueString(node, "Value") + return visitor.ActionUpdate, getMapValueString(node, "Value") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "EnumValue": func(p VisitFuncParams) (string, interface{}) { + "EnumValue": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, getMapValueString(node, "Value") + return visitor.ActionUpdate, getMapValueString(node, "Value") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "ListValue": func(p VisitFuncParams) (string, interface{}) { + "ListValue": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, "[" + join(toSliceString(getMapValue(node, "Values")), ", ") + "]" + return visitor.ActionUpdate, "[" + join(toSliceString(getMapValue(node, "Values")), ", ") + "]" } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "ObjectValue": func(p VisitFuncParams) (string, interface{}) { + "ObjectValue": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, "{" + join(toSliceString(getMapValue(node, "Fields")), ", ") + "}" + return visitor.ActionUpdate, "{" + join(toSliceString(getMapValue(node, "Fields")), ", ") + "}" } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "ObjectField": func(p VisitFuncParams) (string, interface{}) { + "ObjectField": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") value := getMapValueString(node, "Value") - return ActionUpdate, name + ": " + value + return visitor.ActionUpdate, name + ": " + value } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "Directive": func(p VisitFuncParams) (string, interface{}) { + "Directive": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") args := toSliceString(getMapValue(node, "Arguments")) - return ActionUpdate, "@" + name + wrap("(", join(args, ", "), ")") + return visitor.ActionUpdate, "@" + name + wrap("(", join(args, ", "), ")") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "Named": func(p VisitFuncParams) (string, interface{}) { + "Named": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, getMapValueString(node, "Name") + return visitor.ActionUpdate, getMapValueString(node, "Name") } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "List": func(p VisitFuncParams) (string, interface{}) { + "List": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, "[" + getMapValueString(node, "Type") + "]" + return visitor.ActionUpdate, "[" + getMapValueString(node, "Type") + "]" } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "NonNull": func(p VisitFuncParams) (string, interface{}) { + "NonNull": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: - return ActionUpdate, getMapValueString(node, "Type") + "!" + return visitor.ActionUpdate, getMapValueString(node, "Type") + "!" } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "ObjectDefinition": func(p VisitFuncParams) (string, interface{}) { + "ObjectDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") interfaces := toSliceString(getMapValue(node, "Interfaces")) fields := getMapValue(node, "Fields") str := "type " + name + " " + wrap("implements ", join(interfaces, ", "), " ") + block(fields) - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "FieldDefinition": func(p VisitFuncParams) (string, interface{}) { + "FieldDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") ttype := getMapValueString(node, "Type") args := toSliceString(getMapValue(node, "Arguments")) str := name + wrap("(", join(args, ", "), ")") + ": " + ttype - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "InputValueDefinition": func(p VisitFuncParams) (string, interface{}) { + "InputValueDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") ttype := getMapValueString(node, "Type") defaultValue := getMapValueString(node, "DefaultValue") str := name + ": " + ttype + wrap(" = ", defaultValue, "") - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "InterfaceDefinition": func(p VisitFuncParams) (string, interface{}) { + "InterfaceDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") fields := getMapValue(node, "Fields") str := "interface " + name + " " + block(fields) - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "UnionDefinition": func(p VisitFuncParams) (string, interface{}) { + "UnionDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") types := toSliceString(getMapValue(node, "Types")) str := "union " + name + " = " + join(types, " | ") - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "ScalarDefinition": func(p VisitFuncParams) (string, interface{}) { + "ScalarDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") str := "scalar " + name - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "EnumDefinition": func(p VisitFuncParams) (string, interface{}) { + "EnumDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") values := getMapValue(node, "Values") str := "enum " + name + " " + block(values) - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "EnumValueDefinition": func(p VisitFuncParams) (string, interface{}) { + "EnumValueDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") - return ActionUpdate, name + return visitor.ActionUpdate, name } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "InputObjectDefinition": func(p VisitFuncParams) (string, interface{}) { + "InputObjectDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: name := getMapValueString(node, "Name") fields := getMapValue(node, "Fields") - return ActionUpdate, "input " + name + " " + block(fields) + return visitor.ActionUpdate, "input " + name + " " + block(fields) } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, - "TypeExtensionDefinition": func(p VisitFuncParams) (string, interface{}) { + "TypeExtensionDefinition": func(p visitor.VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { case map[string]interface{}: definition := getMapValueString(node, "Definition") str := "extend " + definition - return ActionUpdate, str + return visitor.ActionUpdate, str } - return ActionNoChange, nil + return visitor.ActionNoChange, nil }, } -func Print(astNode Node) (printed interface{}) { +func Print(astNode ast.Node) (printed interface{}) { defer func() interface{} { if r := recover(); r != nil { return fmt.Sprintf("%v", astNode) } return printed }() - printed = Visit(astNode, &VisitorOptions{ + printed = visitor.Visit(astNode, &visitor.VisitorOptions{ LeaveKindMap: printDocASTReducer, }, nil) return printed diff --git a/printer_test.go b/language/printer/printer_test.go similarity index 99% rename from printer_test.go rename to language/printer/printer_test.go index 1de7f935..9fcf31c6 100644 --- a/printer_test.go +++ b/language/printer/printer_test.go @@ -1,4 +1,4 @@ -package graphql +package printer import ( "io/ioutil" diff --git a/schema_printer_test.go b/language/printer/schema_printer_test.go similarity index 99% rename from schema_printer_test.go rename to language/printer/schema_printer_test.go index 8c60113b..e5e9bc33 100644 --- a/schema_printer_test.go +++ b/language/printer/schema_printer_test.go @@ -1,4 +1,4 @@ -package graphql +package printer import ( "io/ioutil" diff --git a/source.go b/language/source/source.go similarity index 92% rename from source.go rename to language/source/source.go index 85332839..c75192d4 100644 --- a/source.go +++ b/language/source/source.go @@ -1,4 +1,4 @@ -package graphql +package source const ( name = "GraphQL" diff --git a/visitor.go b/language/visitor/visitor.go similarity index 99% rename from visitor.go rename to language/visitor/visitor.go index ceada812..09297379 100644 --- a/visitor.go +++ b/language/visitor/visitor.go @@ -1,4 +1,4 @@ -package graphql +package visitor import ( "encoding/json" diff --git a/visitor_test.go b/language/visitor/visitor_test.go similarity index 95% rename from visitor_test.go rename to language/visitor/visitor_test.go index 2959e78b..f59ca016 100644 --- a/visitor_test.go +++ b/language/visitor/visitor_test.go @@ -1,16 +1,22 @@ -package graphql +package visitor import ( + "encoding/json" "io/ioutil" "reflect" "strings" "testing" + + "github.com/chris-ramon/graphql" + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/kr/pretty" ) -func parseeee(t *testing.T, query string) *AstDocument { - astDoc, err := Parse(ParseParams{ +func parse(t *testing.T, query string) *ast.Document { + astDoc, err := graphql.Parse(ParseParams{ Source: query, - Options: ParseOptions{ + Options: graphql.ParseOptions{ NoLocation: true, }, }) @@ -63,10 +69,10 @@ func testGetMapValueString(m map[string]interface{}, key string) string { func TestVisitor_AllowsForEditingOnEnter(t *testing.T) { query := `{ a, b, c { a, b, c } }` - astDoc := parseeee(t, query) + astDoc := parse(t, query) expectedQuery := `{ a, c { a, c } }` - expectedAST := parseeee(t, expectedQuery) + expectedAST := parse(t, expectedQuery) v := &VisitorOptions{ Enter: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { @@ -88,10 +94,10 @@ func TestVisitor_AllowsForEditingOnEnter(t *testing.T) { func TestVisitor_AllowsForEditingOnLeave(t *testing.T) { query := `{ a, b, c { a, b, c } }` - astDoc := parseeee(t, query) + astDoc := parse(t, query) expectedQuery := `{ a, c { a, c } }` - expectedAST := parseeee(t, expectedQuery) + expectedAST := parse(t, expectedQuery) v := &VisitorOptions{ Leave: func(p VisitFuncParams) (string, interface{}) { switch node := p.Node.(type) { @@ -113,7 +119,7 @@ func TestVisitor_AllowsForEditingOnLeave(t *testing.T) { func TestVisitor_VisitsEditedNode(t *testing.T) { query := `{ a { x } }` - astDoc := parseeee(t, query) + astDoc := parse(t, query) addedField := map[string]interface{}{ "Kind": "Field", @@ -152,7 +158,7 @@ func TestVisitor_VisitsEditedNode(t *testing.T) { func TestVisitor_AllowsSkippingASubTree(t *testing.T) { query := `{ a, b { x }, c }` - astDoc := parseeee(t, query) + astDoc := parse(t, query) visited := []interface{}{} expectedVisited := []interface{}{ @@ -203,7 +209,7 @@ func TestVisitor_AllowsSkippingASubTree(t *testing.T) { func TestVisitor_AllowsANamedFunctionsVisitorAPI(t *testing.T) { query := `{ a, b { x }, c }` - astDoc := parseeee(t, query) + astDoc := parse(t, query) visited := []interface{}{} expectedVisited := []interface{}{ @@ -260,7 +266,7 @@ func TestVisitor_VisitsKitchenSink(t *testing.T) { } query := string(b) - astDoc := parseeee(t, query) + astDoc := parse(t, query) visited := []interface{}{} expectedVisited := []interface{}{ @@ -533,3 +539,20 @@ func TestVisitor_ProducesHelpfulErrorMessages(t *testing.T) { } _ = Visit(astDoc, nil, nil) } + +func ASTToJSON(t *testing.T, a ast.Node) interface{} { + b, err := json.Marshal(a) + if err != nil { + t.Fatalf("Failed to marshal Node %v", err) + } + var f interface{} + err = json.Unmarshal(b, &f) + if err != nil { + t.Fatalf("Failed to unmarshal Node %v", err) + } + return f +} + +func Diff(a, b interface{}) []string { + return pretty.Diff(a, b) +} diff --git a/lists_test.go b/lists_test.go index 57dfd0d4..b14b8223 100644 --- a/lists_test.go +++ b/lists_test.go @@ -3,6 +3,9 @@ package graphql import ( "reflect" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/location" ) func checkList(t *testing.T, testType Type, testData interface{}, expected *Result) { @@ -249,11 +252,11 @@ func TestLists_NonNullListOfNullableObjectsReturnsNull(t *testing.T) { Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 1, Column: 10, }, @@ -319,11 +322,11 @@ func TestLists_NonNullListOfNullableFunc_ReturnsNull(t *testing.T) { Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 1, Column: 10, }, @@ -415,11 +418,11 @@ func TestLists_NullableListOfNonNullObjects_ContainsNull(t *testing.T) { "test": nil, }, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 1, Column: 10, }, @@ -480,11 +483,11 @@ func TestLists_NullableListOfNonNullFunc_ContainsNull(t *testing.T) { "test": nil, }, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 1, Column: 10, }, @@ -591,11 +594,11 @@ func TestLists_NonNullListOfNonNullObjects_ContainsNull(t *testing.T) { Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 1, Column: 10, }, @@ -612,11 +615,11 @@ func TestLists_NonNullListOfNonNullObjects_ReturnsNull(t *testing.T) { Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 1, Column: 10, }, @@ -663,11 +666,11 @@ func TestLists_NonNullListOfNonNullFunc_ContainsNull(t *testing.T) { Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 1, Column: 10, }, @@ -689,11 +692,11 @@ func TestLists_NonNullListOfNonNullFunc_ReturnsNull(t *testing.T) { Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: "Cannot return null for non-nullable field DataType.test.", - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 1, Column: 10, }, diff --git a/located.go b/located.go index f655c212..2f741ae7 100644 --- a/located.go +++ b/located.go @@ -1,6 +1,11 @@ package graphql -func NewLocatedError(err interface{}, nodes []Node) *Error { +import ( + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/ast" +) + +func NewLocatedError(err interface{}, nodes []ast.Node) *gqlerrors.Error { message := "An unknown error occurred." if err, ok := err.(error); ok { message = err.Error() @@ -9,7 +14,7 @@ func NewLocatedError(err interface{}, nodes []Node) *Error { message = err } stack := message - return NewError( + return gqlerrors.NewError( message, nodes, stack, @@ -18,8 +23,8 @@ func NewLocatedError(err interface{}, nodes []Node) *Error { ) } -func FieldASTsToNodeASTs(fieldASTs []*AstField) []Node { - nodes := []Node{} +func FieldASTsToNodeASTs(fieldASTs []*ast.Field) []ast.Node { + nodes := []ast.Node{} for _, fieldAST := range fieldASTs { nodes = append(nodes, fieldAST) } diff --git a/mutations_test.go b/mutations_test.go index 58ba158b..c905305f 100644 --- a/mutations_test.go +++ b/mutations_test.go @@ -3,6 +3,9 @@ package graphql import ( "reflect" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/location" ) // testNumberHolder maps to numberHolderType @@ -212,17 +215,17 @@ func TestMutations_EvaluatesMutationsCorrectlyInThePresenceOfAFailedMutation(t * }, "sixth": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot change the number`, - Locations: []SourceLocation{ - SourceLocation{Line: 8, Column: 7}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 8, Column: 7}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot change the number`, - Locations: []SourceLocation{ - SourceLocation{Line: 17, Column: 7}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 17, Column: 7}, }, }, }, diff --git a/nonnull_test.go b/nonnull_test.go index bc53957b..b208ca1a 100644 --- a/nonnull_test.go +++ b/nonnull_test.go @@ -4,6 +4,9 @@ import ( "reflect" "sort" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/location" ) var syncError = "sync" @@ -115,11 +118,11 @@ func TestNonNull_NullsANullableFieldThatThrowsSynchronously(t *testing.T) { Data: map[string]interface{}{ "sync": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: syncError, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 3, Column: 9, }, }, @@ -153,11 +156,11 @@ func TestNonNull_NullsANullableFieldThatThrowsInAPromise(t *testing.T) { Data: map[string]interface{}{ "promise": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: promiseError, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 3, Column: 9, }, }, @@ -193,11 +196,11 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANullableFieldThat Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: nonNullSyncError, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 4, Column: 11, }, }, @@ -233,11 +236,11 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: nonNullPromiseError, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 4, Column: 11, }, }, @@ -273,11 +276,11 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: nonNullSyncError, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 4, Column: 11, }, }, @@ -313,11 +316,11 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: nonNullPromiseError, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 4, Column: 11, }, }, @@ -398,77 +401,77 @@ func TestNonNull_NullsAComplexTreeOfNullableFieldsThatThrow(t *testing.T) { }, }, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: syncError, - Locations: []SourceLocation{ - SourceLocation{Line: 4, Column: 11}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 4, Column: 11}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: syncError, - Locations: []SourceLocation{ - SourceLocation{Line: 7, Column: 13}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 7, Column: 13}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: syncError, - Locations: []SourceLocation{ - SourceLocation{Line: 11, Column: 13}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 11, Column: 13}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: syncError, - Locations: []SourceLocation{ - SourceLocation{Line: 16, Column: 11}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 16, Column: 11}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: syncError, - Locations: []SourceLocation{ - SourceLocation{Line: 19, Column: 13}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 19, Column: 13}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: syncError, - Locations: []SourceLocation{ - SourceLocation{Line: 23, Column: 13}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 23, Column: 13}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: promiseError, - Locations: []SourceLocation{ - SourceLocation{Line: 5, Column: 11}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 5, Column: 11}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: promiseError, - Locations: []SourceLocation{ - SourceLocation{Line: 8, Column: 13}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 8, Column: 13}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: promiseError, - Locations: []SourceLocation{ - SourceLocation{Line: 12, Column: 13}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 12, Column: 13}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: promiseError, - Locations: []SourceLocation{ - SourceLocation{Line: 17, Column: 11}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 17, Column: 11}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: promiseError, - Locations: []SourceLocation{ - SourceLocation{Line: 20, Column: 13}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 20, Column: 13}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: promiseError, - Locations: []SourceLocation{ - SourceLocation{Line: 24, Column: 13}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 24, Column: 13}, }, }, }, @@ -489,8 +492,8 @@ func TestNonNull_NullsAComplexTreeOfNullableFieldsThatThrow(t *testing.T) { if !reflect.DeepEqual(expected.Data, result.Data) { t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Data, result.Data)) } - sort.Sort(GQLFormattedErrorSlice(expected.Errors)) - sort.Sort(GQLFormattedErrorSlice(result.Errors)) + sort.Sort(gqlerrors.GQLFormattedErrorSlice(expected.Errors)) + sort.Sort(gqlerrors.GQLFormattedErrorSlice(result.Errors)) if !reflect.DeepEqual(expected.Errors, result.Errors) { t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Errors, result.Errors)) } @@ -551,29 +554,29 @@ func TestNonNull_NullsTheFirstNullableObjectAfterAFieldThrowsInALongChainOfField "anotherNest": nil, "anotherPromiseNest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: nonNullSyncError, - Locations: []SourceLocation{ - SourceLocation{Line: 8, Column: 19}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 8, Column: 19}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: nonNullSyncError, - Locations: []SourceLocation{ - SourceLocation{Line: 19, Column: 19}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 19, Column: 19}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: nonNullPromiseError, - Locations: []SourceLocation{ - SourceLocation{Line: 30, Column: 19}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 30, Column: 19}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: nonNullPromiseError, - Locations: []SourceLocation{ - SourceLocation{Line: 41, Column: 19}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 41, Column: 19}, }, }, }, @@ -594,8 +597,8 @@ func TestNonNull_NullsTheFirstNullableObjectAfterAFieldThrowsInALongChainOfField if !reflect.DeepEqual(expected.Data, result.Data) { t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Data, result.Data)) } - sort.Sort(GQLFormattedErrorSlice(expected.Errors)) - sort.Sort(GQLFormattedErrorSlice(result.Errors)) + sort.Sort(gqlerrors.GQLFormattedErrorSlice(expected.Errors)) + sort.Sort(gqlerrors.GQLFormattedErrorSlice(result.Errors)) if !reflect.DeepEqual(expected.Errors, result.Errors) { t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Errors, result.Errors)) } @@ -675,11 +678,11 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []SourceLocation{ - SourceLocation{Line: 4, Column: 11}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 4, Column: 11}, }, }, }, @@ -713,11 +716,11 @@ func TestNonNull_NullsASynchronouslyReturnedObjectThatContainsANonNullableFieldT Data: map[string]interface{}{ "nest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []SourceLocation{ - SourceLocation{Line: 4, Column: 11}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 4, Column: 11}, }, }, }, @@ -752,11 +755,11 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []SourceLocation{ - SourceLocation{Line: 4, Column: 11}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 4, Column: 11}, }, }, }, @@ -790,11 +793,11 @@ func TestNonNull_NullsAnObjectReturnedInAPromiseThatContainsANonNullableFieldTha Data: map[string]interface{}{ "promiseNest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []SourceLocation{ - SourceLocation{Line: 4, Column: 11}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 4, Column: 11}, }, }, }, @@ -949,29 +952,29 @@ func TestNonNull_NullsTheFirstNullableObjectAfterAFieldReturnsNullInALongChainOf "anotherNest": nil, "anotherPromiseNest": nil, }, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []SourceLocation{ - SourceLocation{Line: 8, Column: 19}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 8, Column: 19}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []SourceLocation{ - SourceLocation{Line: 19, Column: 19}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 19, Column: 19}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []SourceLocation{ - SourceLocation{Line: 30, Column: 19}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 30, Column: 19}, }, }, - FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []SourceLocation{ - SourceLocation{Line: 41, Column: 19}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 41, Column: 19}, }, }, }, @@ -992,8 +995,8 @@ func TestNonNull_NullsTheFirstNullableObjectAfterAFieldReturnsNullInALongChainOf if !reflect.DeepEqual(expected.Data, result.Data) { t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Data, result.Data)) } - sort.Sort(GQLFormattedErrorSlice(expected.Errors)) - sort.Sort(GQLFormattedErrorSlice(result.Errors)) + sort.Sort(gqlerrors.GQLFormattedErrorSlice(expected.Errors)) + sort.Sort(gqlerrors.GQLFormattedErrorSlice(result.Errors)) if !reflect.DeepEqual(expected.Errors, result.Errors) { t.Fatalf("Unexpected result, Diff: %v", Diff(expected.Errors, result.Errors)) } @@ -1005,11 +1008,11 @@ func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldThrows(t *testing.T) { ` expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: nonNullSyncError, - Locations: []SourceLocation{ - SourceLocation{Line: 2, Column: 17}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 2, Column: 17}, }, }, }, @@ -1037,11 +1040,11 @@ func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldErrors(t *testing.T) { ` expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: nonNullPromiseError, - Locations: []SourceLocation{ - SourceLocation{Line: 2, Column: 17}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 2, Column: 17}, }, }, }, @@ -1069,11 +1072,11 @@ func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldReturnsNull(t *testing.T) ` expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullSync.`, - Locations: []SourceLocation{ - SourceLocation{Line: 2, Column: 17}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 2, Column: 17}, }, }, }, @@ -1101,11 +1104,11 @@ func TestNonNull_NullsTheTopLevelIfSyncNonNullableFieldResolvesNull(t *testing.T ` expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Cannot return null for non-nullable field DataType.nonNullPromise.`, - Locations: []SourceLocation{ - SourceLocation{Line: 2, Column: 17}, + Locations: []location.SourceLocation{ + location.SourceLocation{Line: 2, Column: 17}, }, }, }, diff --git a/parser.go b/parser.go index d223f844..9ae4a0b8 100644 --- a/parser.go +++ b/parser.go @@ -2,6 +2,11 @@ package graphql import ( "fmt" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/lexer" + "github.com/chris-ramon/graphql/language/source" ) type parseFn func(parser *Parser) (interface{}, error) @@ -17,21 +22,21 @@ type ParseParams struct { } type Parser struct { - LexToken Lexer - Source *Source + LexToken lexer.Lexer + Source *source.Source Options ParseOptions PrevEnd int - Token Token + Token lexer.Token } -func Parse(p ParseParams) (*AstDocument, error) { - var sourceObj *Source +func Parse(p ParseParams) (*ast.Document, error) { + var sourceObj *source.Source switch p.Source.(type) { - case *Source: - sourceObj = p.Source.(*Source) + case *source.Source: + sourceObj = p.Source.(*source.Source) default: body, _ := p.Source.(string) - sourceObj = NewSource(&Source{Body: body}) + sourceObj = source.NewSource(&source.Source{Body: body}) } parser, err := makeParser(sourceObj, p.Options) if err != nil { @@ -45,15 +50,15 @@ func Parse(p ParseParams) (*AstDocument, error) { } // TODO: test and expose parseValue as a public -func parseValue(p ParseParams) (Value, error) { - var value Value - var sourceObj *Source +func parseValue(p ParseParams) (ast.Value, error) { + var value ast.Value + var sourceObj *source.Source switch p.Source.(type) { - case *Source: - sourceObj = p.Source.(*Source) + case *source.Source: + sourceObj = p.Source.(*source.Source) default: body, _ := p.Source.(string) - sourceObj = NewSource(&Source{Body: body}) + sourceObj = source.NewSource(&source.Source{Body: body}) } parser, err := makeParser(sourceObj, p.Options) if err != nil { @@ -67,19 +72,19 @@ func parseValue(p ParseParams) (Value, error) { } // Converts a name lex token into a name parse node. -func parseName(parser *Parser) (*AstName, error) { - token, err := expect(parser, TokenKind[NAME]) +func parseName(parser *Parser) (*ast.Name, error) { + token, err := expect(parser, lexer.TokenKind[lexer.NAME]) if err != nil { return nil, err } - return NewAstName(&AstName{ + return ast.NewName(&ast.Name{ Value: token.Value, Loc: loc(parser, token.Start), }), nil } -func makeParser(s *Source, opts ParseOptions) (*Parser, error) { - lexToken := Lex(s) +func makeParser(s *source.Source, opts ParseOptions) (*Parser, error) { + lexToken := lexer.Lex(s) token, err := lexToken(0) if err != nil { return &Parser{}, err @@ -93,22 +98,22 @@ func makeParser(s *Source, opts ParseOptions) (*Parser, error) { }, nil } -/* Implements the parsing rules in the AstDocument section. */ +/* Implements the parsing rules in the Document section. */ -func parseDocument(parser *Parser) (*AstDocument, error) { +func parseDocument(parser *Parser) (*ast.Document, error) { start := parser.Token.Start - var nodes []Node + var nodes []ast.Node for { - if skip(parser, TokenKind[EOF]) { + if skip(parser, lexer.TokenKind[lexer.EOF]) { break } - if peek(parser, TokenKind[BRACE_L]) { + if peek(parser, lexer.TokenKind[lexer.BRACE_L]) { node, err := parseOperationDefinition(parser) if err != nil { return nil, err } nodes = append(nodes, node) - } else if peek(parser, TokenKind[NAME]) { + } else if peek(parser, lexer.TokenKind[lexer.NAME]) { switch parser.Token.Value { case "query": fallthrough @@ -169,17 +174,17 @@ func parseDocument(parser *Parser) (*AstDocument, error) { } nodes = append(nodes, node) default: - if err := unexpected(parser, Token{}); err != nil { + if err := unexpected(parser, lexer.Token{}); err != nil { return nil, err } } } else { - if err := unexpected(parser, Token{}); err != nil { + if err := unexpected(parser, lexer.Token{}); err != nil { return nil, err } } } - return NewAstDocument(&AstDocument{ + return ast.NewDocument(&ast.Document{ Loc: loc(parser, start), Definitions: nodes, }), nil @@ -187,21 +192,21 @@ func parseDocument(parser *Parser) (*AstDocument, error) { /* Implements the parsing rules in the Operations section. */ -func parseOperationDefinition(parser *Parser) (*AstOperationDefinition, error) { +func parseOperationDefinition(parser *Parser) (*ast.OperationDefinition, error) { start := parser.Token.Start - if peek(parser, TokenKind[BRACE_L]) { + if peek(parser, lexer.TokenKind[lexer.BRACE_L]) { selectionSet, err := parseSelectionSet(parser) if err != nil { return nil, err } - return NewAstOperationDefinition(&AstOperationDefinition{ + return ast.NewOperationDefinition(&ast.OperationDefinition{ Operation: "query", - Directives: []*AstDirective{}, + Directives: []*ast.Directive{}, SelectionSet: selectionSet, Loc: loc(parser, start), }), nil } - operationToken, err := expect(parser, TokenKind[NAME]) + operationToken, err := expect(parser, lexer.TokenKind[lexer.NAME]) if err != nil { return nil, err } @@ -222,7 +227,7 @@ func parseOperationDefinition(parser *Parser) (*AstOperationDefinition, error) { if err != nil { return nil, err } - return NewAstOperationDefinition(&AstOperationDefinition{ + return ast.NewOperationDefinition(&ast.OperationDefinition{ Operation: operation, Name: name, VariableDefinitions: variableDefinitions, @@ -232,13 +237,13 @@ func parseOperationDefinition(parser *Parser) (*AstOperationDefinition, error) { }), nil } -func parseVariableDefinitions(parser *Parser) ([]*AstVariableDefinition, error) { - variableDefinitions := []*AstVariableDefinition{} - if peek(parser, TokenKind[PAREN_L]) { - vdefs, err := many(parser, TokenKind[PAREN_L], parseVariableDefinition, TokenKind[PAREN_R]) +func parseVariableDefinitions(parser *Parser) ([]*ast.VariableDefinition, error) { + variableDefinitions := []*ast.VariableDefinition{} + if peek(parser, lexer.TokenKind[lexer.PAREN_L]) { + vdefs, err := many(parser, lexer.TokenKind[lexer.PAREN_L], parseVariableDefinition, lexer.TokenKind[lexer.PAREN_R]) for _, vdef := range vdefs { if vdef != nil { - variableDefinitions = append(variableDefinitions, vdef.(*AstVariableDefinition)) + variableDefinitions = append(variableDefinitions, vdef.(*ast.VariableDefinition)) } } if err != nil { @@ -255,7 +260,7 @@ func parseVariableDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - _, err = expect(parser, TokenKind[COLON]) + _, err = expect(parser, lexer.TokenKind[lexer.COLON]) if err != nil { return nil, err } @@ -263,15 +268,15 @@ func parseVariableDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - var defaultValue Value - if skip(parser, TokenKind[EQUALS]) { + var defaultValue ast.Value + if skip(parser, lexer.TokenKind[lexer.EQUALS]) { dv, err := parseValueLiteral(parser, true) if err != nil { return nil, err } defaultValue = dv } - return NewAstVariableDefinition(&AstVariableDefinition{ + return ast.NewVariableDefinition(&ast.VariableDefinition{ Variable: variable, Type: ttype, DefaultValue: defaultValue, @@ -279,9 +284,9 @@ func parseVariableDefinition(parser *Parser) (interface{}, error) { }), nil } -func parseVariable(parser *Parser) (*AstVariable, error) { +func parseVariable(parser *Parser) (*ast.Variable, error) { start := parser.Token.Start - _, err := expect(parser, TokenKind[DOLLAR]) + _, err := expect(parser, lexer.TokenKind[lexer.DOLLAR]) if err != nil { return nil, err } @@ -289,34 +294,34 @@ func parseVariable(parser *Parser) (*AstVariable, error) { if err != nil { return nil, err } - return NewAstVariable(&AstVariable{ + return ast.NewVariable(&ast.Variable{ Name: name, Loc: loc(parser, start), }), nil } -func parseSelectionSet(parser *Parser) (*AstSelectionSet, error) { +func parseSelectionSet(parser *Parser) (*ast.SelectionSet, error) { start := parser.Token.Start - iSelections, err := many(parser, TokenKind[BRACE_L], parseSelection, TokenKind[BRACE_R]) + iSelections, err := many(parser, lexer.TokenKind[lexer.BRACE_L], parseSelection, lexer.TokenKind[lexer.BRACE_R]) if err != nil { return nil, err } - selections := []Selection{} + selections := []ast.Selection{} for _, iSelection := range iSelections { if iSelection != nil { // type assert interface{} into Selection interface - selections = append(selections, iSelection.(Selection)) + selections = append(selections, iSelection.(ast.Selection)) } } - return NewAstSelectionSet(&AstSelectionSet{ + return ast.NewSelectionSet(&ast.SelectionSet{ Selections: selections, Loc: loc(parser, start), }), nil } func parseSelection(parser *Parser) (interface{}, error) { - if peek(parser, TokenKind[SPREAD]) { + if peek(parser, lexer.TokenKind[lexer.SPREAD]) { r, err := parseFragment(parser) return r, err } else { @@ -324,17 +329,17 @@ func parseSelection(parser *Parser) (interface{}, error) { } } -func parseField(parser *Parser) (*AstField, error) { +func parseField(parser *Parser) (*ast.Field, error) { start := parser.Token.Start nameOrAlias, err := parseName(parser) if err != nil { return nil, err } var ( - name *AstName - alias *AstName + name *ast.Name + alias *ast.Name ) - if skip(parser, TokenKind[COLON]) { + if skip(parser, lexer.TokenKind[lexer.COLON]) { alias = nameOrAlias n, err := parseName(parser) if err != nil { @@ -352,15 +357,15 @@ func parseField(parser *Parser) (*AstField, error) { if err != nil { return nil, err } - var selectionSet *AstSelectionSet - if peek(parser, TokenKind[BRACE_L]) { + var selectionSet *ast.SelectionSet + if peek(parser, lexer.TokenKind[lexer.BRACE_L]) { sSet, err := parseSelectionSet(parser) if err != nil { return nil, err } selectionSet = sSet } - return NewField(&AstField{ + return ast.NewField(&ast.Field{ Alias: alias, Name: name, Arguments: arguments, @@ -370,16 +375,16 @@ func parseField(parser *Parser) (*AstField, error) { }), nil } -func parseArguments(parser *Parser) ([]*AstArgument, error) { - arguments := []*AstArgument{} - if peek(parser, TokenKind[PAREN_L]) { - iArguments, err := many(parser, TokenKind[PAREN_L], parseArgument, TokenKind[PAREN_R]) +func parseArguments(parser *Parser) ([]*ast.Argument, error) { + arguments := []*ast.Argument{} + if peek(parser, lexer.TokenKind[lexer.PAREN_L]) { + iArguments, err := many(parser, lexer.TokenKind[lexer.PAREN_L], parseArgument, lexer.TokenKind[lexer.PAREN_R]) if err != nil { return arguments, err } for _, iArgument := range iArguments { if iArgument != nil { - arguments = append(arguments, iArgument.(*AstArgument)) + arguments = append(arguments, iArgument.(*ast.Argument)) } } return arguments, nil @@ -393,7 +398,7 @@ func parseArgument(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - _, err = expect(parser, TokenKind[COLON]) + _, err = expect(parser, lexer.TokenKind[lexer.COLON]) if err != nil { return nil, err } @@ -401,7 +406,7 @@ func parseArgument(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return NewAstArgument(&AstArgument{ + return ast.NewArgument(&ast.Argument{ Name: name, Value: value, Loc: loc(parser, start), @@ -412,7 +417,7 @@ func parseArgument(parser *Parser) (interface{}, error) { func parseFragment(parser *Parser) (interface{}, error) { start := parser.Token.Start - _, err := expect(parser, TokenKind[SPREAD]) + _, err := expect(parser, lexer.TokenKind[lexer.SPREAD]) if err != nil { return nil, err } @@ -430,7 +435,7 @@ func parseFragment(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return NewAstInlineFragment(&AstInlineFragment{ + return ast.NewInlineFragment(&ast.InlineFragment{ TypeCondition: name, Directives: directives, SelectionSet: selectionSet, @@ -445,14 +450,14 @@ func parseFragment(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return NewAstFragmentSpread(&AstFragmentSpread{ + return ast.NewFragmentSpread(&ast.FragmentSpread{ Name: name, Directives: directives, Loc: loc(parser, start), }), nil } -func parseFragmentDefinition(parser *Parser) (*AstFragmentDefinition, error) { +func parseFragmentDefinition(parser *Parser) (*ast.FragmentDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "fragment") if err != nil { @@ -478,7 +483,7 @@ func parseFragmentDefinition(parser *Parser) (*AstFragmentDefinition, error) { if err != nil { return nil, err } - return NewAstFragmentDefinition(&AstFragmentDefinition{ + return ast.NewFragmentDefinition(&ast.FragmentDefinition{ Name: name, TypeCondition: typeCondition, Directives: directives, @@ -487,64 +492,64 @@ func parseFragmentDefinition(parser *Parser) (*AstFragmentDefinition, error) { }), nil } -func parseFragmentName(parser *Parser) (*AstName, error) { +func parseFragmentName(parser *Parser) (*ast.Name, error) { if parser.Token.Value == "on" { - return nil, unexpected(parser, Token{}) + return nil, unexpected(parser, lexer.Token{}) } return parseName(parser) } /* Implements the parsing rules in the Values section. */ -func parseValueLiteral(parser *Parser, isConst bool) (Value, error) { +func parseValueLiteral(parser *Parser, isConst bool) (ast.Value, error) { token := parser.Token switch token.Kind { - case TokenKind[BRACKET_L]: + case lexer.TokenKind[lexer.BRACKET_L]: return parseList(parser, isConst) - case TokenKind[BRACE_L]: + case lexer.TokenKind[lexer.BRACE_L]: return parseObject(parser, isConst) - case TokenKind[INT]: + case lexer.TokenKind[lexer.INT]: advance(parser) - return NewAstIntValue(&AstIntValue{ + return ast.NewIntValue(&ast.IntValue{ Value: token.Value, Loc: loc(parser, token.Start), }), nil - case TokenKind[FLOAT]: + case lexer.TokenKind[lexer.FLOAT]: advance(parser) - return NewAstFloatValue(&AstFloatValue{ + return ast.NewFloatValue(&ast.FloatValue{ Value: token.Value, Loc: loc(parser, token.Start), }), nil - case TokenKind[STRING]: + case lexer.TokenKind[lexer.STRING]: advance(parser) - return NewAstStringValue(&AstStringValue{ + return ast.NewStringValue(&ast.StringValue{ Value: token.Value, Loc: loc(parser, token.Start), }), nil - case TokenKind[NAME]: + case lexer.TokenKind[lexer.NAME]: if token.Value == "true" || token.Value == "false" { advance(parser) value := true if token.Value == "false" { value = false } - return NewAstBooleanValue(&AstBooleanValue{ + return ast.NewBooleanValue(&ast.BooleanValue{ Value: value, Loc: loc(parser, token.Start), }), nil } else if token.Value != "null" { advance(parser) - return NewAstEnumValue(&AstEnumValue{ + return ast.NewEnumValue(&ast.EnumValue{ Value: token.Value, Loc: loc(parser, token.Start), }), nil } - case TokenKind[DOLLAR]: + case lexer.TokenKind[lexer.DOLLAR]: if !isConst { return parseVariable(parser) } } - if err := unexpected(parser, Token{}); err != nil { + if err := unexpected(parser, lexer.Token{}); err != nil { return nil, err } return nil, nil @@ -562,7 +567,7 @@ func parseValueValue(parser *Parser) (interface{}, error) { return parseValueLiteral(parser, false) } -func parseList(parser *Parser, isConst bool) (*AstListValue, error) { +func parseList(parser *Parser, isConst bool) (*ast.ListValue, error) { start := parser.Token.Start var item parseFn if isConst { @@ -570,30 +575,30 @@ func parseList(parser *Parser, isConst bool) (*AstListValue, error) { } else { item = parseValueValue } - iValues, err := any(parser, TokenKind[BRACKET_L], item, TokenKind[BRACKET_R]) + iValues, err := any(parser, lexer.TokenKind[lexer.BRACKET_L], item, lexer.TokenKind[lexer.BRACKET_R]) if err != nil { return nil, err } - values := []Value{} + values := []ast.Value{} for _, iValue := range iValues { - values = append(values, iValue.(Value)) + values = append(values, iValue.(ast.Value)) } - return NewAstListValue(&AstListValue{ + return ast.NewListValue(&ast.ListValue{ Values: values, Loc: loc(parser, start), }), nil } -func parseObject(parser *Parser, isConst bool) (*AstObjectValue, error) { +func parseObject(parser *Parser, isConst bool) (*ast.ObjectValue, error) { start := parser.Token.Start - _, err := expect(parser, TokenKind[BRACE_L]) + _, err := expect(parser, lexer.TokenKind[lexer.BRACE_L]) if err != nil { return nil, err } - fields := []*AstObjectField{} + fields := []*ast.ObjectField{} fieldNames := map[string]bool{} for { - if skip(parser, TokenKind[BRACE_R]) { + if skip(parser, lexer.TokenKind[lexer.BRACE_R]) { break } field, fieldName, err := parseObjectField(parser, isConst, fieldNames) @@ -603,13 +608,13 @@ func parseObject(parser *Parser, isConst bool) (*AstObjectValue, error) { fieldNames[fieldName] = true fields = append(fields, field) } - return NewAstObjectValue(&AstObjectValue{ + return ast.NewObjectValue(&ast.ObjectValue{ Fields: fields, Loc: loc(parser, start), }), nil } -func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) (*AstObjectField, string, error) { +func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) (*ast.ObjectField, string, error) { start := parser.Token.Start name, err := parseName(parser) if err != nil { @@ -618,9 +623,9 @@ func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) fieldName := name.Value if _, ok := fieldNames[fieldName]; ok { descp := fmt.Sprintf("Duplicate input object field %v.", fieldName) - return nil, "", NewSyntaxError(parser.Source, start, descp) + return nil, "", gqlerrors.NewSyntaxError(parser.Source, start, descp) } - _, err = expect(parser, TokenKind[COLON]) + _, err = expect(parser, lexer.TokenKind[lexer.COLON]) if err != nil { return nil, "", err } @@ -628,7 +633,7 @@ func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) if err != nil { return nil, "", err } - return NewAstObjectField(&AstObjectField{ + return ast.NewObjectField(&ast.ObjectField{ Name: name, Value: value, Loc: loc(parser, start), @@ -637,10 +642,10 @@ func parseObjectField(parser *Parser, isConst bool, fieldNames map[string]bool) /* Implements the parsing rules in the Directives section. */ -func parseDirectives(parser *Parser) ([]*AstDirective, error) { - directives := []*AstDirective{} +func parseDirectives(parser *Parser) ([]*ast.Directive, error) { + directives := []*ast.Directive{} for { - if !peek(parser, TokenKind[AT]) { + if !peek(parser, lexer.TokenKind[lexer.AT]) { break } directive, err := parseDirective(parser) @@ -652,9 +657,9 @@ func parseDirectives(parser *Parser) ([]*AstDirective, error) { return directives, nil } -func parseDirective(parser *Parser) (*AstDirective, error) { +func parseDirective(parser *Parser) (*ast.Directive, error) { start := parser.Token.Start - _, err := expect(parser, TokenKind[AT]) + _, err := expect(parser, lexer.TokenKind[lexer.AT]) if err != nil { return nil, err } @@ -666,7 +671,7 @@ func parseDirective(parser *Parser) (*AstDirective, error) { if err != nil { return nil, err } - return NewAstDirective(&AstDirective{ + return ast.NewDirective(&ast.Directive{ Name: name, Arguments: args, Loc: loc(parser, start), @@ -675,20 +680,20 @@ func parseDirective(parser *Parser) (*AstDirective, error) { /* Implements the parsing rules in the Types section. */ -func parseType(parser *Parser) (AstType, error) { +func parseType(parser *Parser) (ast.Type, error) { start := parser.Token.Start - var ttype AstType - if skip(parser, TokenKind[BRACKET_L]) { + var ttype ast.Type + if skip(parser, lexer.TokenKind[lexer.BRACKET_L]) { t, err := parseType(parser) if err != nil { return t, err } ttype = t - _, err = expect(parser, TokenKind[BRACKET_R]) + _, err = expect(parser, lexer.TokenKind[lexer.BRACKET_R]) if err != nil { return ttype, err } - ttype = NewAstList(&AstList{ + ttype = ast.NewList(&ast.List{ Type: ttype, Loc: loc(parser, start), }) @@ -699,8 +704,8 @@ func parseType(parser *Parser) (AstType, error) { } ttype = name } - if skip(parser, TokenKind[BANG]) { - ttype = NewAstNonNull(&AstNonNull{ + if skip(parser, lexer.TokenKind[lexer.BANG]) { + ttype = ast.NewNonNull(&ast.NonNull{ Type: ttype, Loc: loc(parser, start), }) @@ -709,13 +714,13 @@ func parseType(parser *Parser) (AstType, error) { return ttype, nil } -func parseNamed(parser *Parser) (*AstNamed, error) { +func parseNamed(parser *Parser) (*ast.Named, error) { start := parser.Token.Start name, err := parseName(parser) if err != nil { return nil, err } - return NewAstNamed(&AstNamed{ + return ast.NewNamed(&ast.Named{ Name: name, Loc: loc(parser, start), }), nil @@ -723,7 +728,7 @@ func parseNamed(parser *Parser) (*AstNamed, error) { /* Implements the parsing rules in the Type Definition section. */ -func parseObjectTypeDefinition(parser *Parser) (*AstObjectDefinition, error) { +func parseObjectTypeDefinition(parser *Parser) (*ast.ObjectDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "type") if err != nil { @@ -737,17 +742,17 @@ func parseObjectTypeDefinition(parser *Parser) (*AstObjectDefinition, error) { if err != nil { return nil, err } - iFields, err := any(parser, TokenKind[BRACE_L], parseFieldDefinition, TokenKind[BRACE_R]) + iFields, err := any(parser, lexer.TokenKind[lexer.BRACE_L], parseFieldDefinition, lexer.TokenKind[lexer.BRACE_R]) if err != nil { return nil, err } - fields := []*AstFieldDefinition{} + fields := []*ast.FieldDefinition{} for _, iField := range iFields { if iField != nil { - fields = append(fields, iField.(*AstFieldDefinition)) + fields = append(fields, iField.(*ast.FieldDefinition)) } } - return NewAstObjectDefinition(&AstObjectDefinition{ + return ast.NewObjectDefinition(&ast.ObjectDefinition{ Name: name, Loc: loc(parser, start), Interfaces: interfaces, @@ -755,8 +760,8 @@ func parseObjectTypeDefinition(parser *Parser) (*AstObjectDefinition, error) { }), nil } -func parseImplementsInterfaces(parser *Parser) ([]*AstNamed, error) { - types := []*AstNamed{} +func parseImplementsInterfaces(parser *Parser) ([]*ast.Named, error) { + types := []*ast.Named{} if parser.Token.Value == "implements" { advance(parser) for { @@ -765,7 +770,7 @@ func parseImplementsInterfaces(parser *Parser) ([]*AstNamed, error) { return types, err } types = append(types, ttype) - if peek(parser, TokenKind[BRACE_L]) { + if peek(parser, lexer.TokenKind[lexer.BRACE_L]) { break } } @@ -783,7 +788,7 @@ func parseFieldDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - _, err = expect(parser, TokenKind[COLON]) + _, err = expect(parser, lexer.TokenKind[lexer.COLON]) if err != nil { return nil, err } @@ -791,7 +796,7 @@ func parseFieldDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return NewAstFieldDefinition(&AstFieldDefinition{ + return ast.NewFieldDefinition(&ast.FieldDefinition{ Name: name, Arguments: args, Type: ttype, @@ -799,19 +804,19 @@ func parseFieldDefinition(parser *Parser) (interface{}, error) { }), nil } -func parseArgumentDefs(parser *Parser) ([]*AstInputValueDefinition, error) { - inputValueDefinitions := []*AstInputValueDefinition{} +func parseArgumentDefs(parser *Parser) ([]*ast.InputValueDefinition, error) { + inputValueDefinitions := []*ast.InputValueDefinition{} - if !peek(parser, TokenKind[PAREN_L]) { + if !peek(parser, lexer.TokenKind[lexer.PAREN_L]) { return inputValueDefinitions, nil } - iInputValueDefinitions, err := many(parser, TokenKind[PAREN_L], parseInputValueDef, TokenKind[PAREN_R]) + iInputValueDefinitions, err := many(parser, lexer.TokenKind[lexer.PAREN_L], parseInputValueDef, lexer.TokenKind[lexer.PAREN_R]) if err != nil { return inputValueDefinitions, err } for _, iInputValueDefinition := range iInputValueDefinitions { if iInputValueDefinition != nil { - inputValueDefinitions = append(inputValueDefinitions, iInputValueDefinition.(*AstInputValueDefinition)) + inputValueDefinitions = append(inputValueDefinitions, iInputValueDefinition.(*ast.InputValueDefinition)) } } return inputValueDefinitions, err @@ -823,7 +828,7 @@ func parseInputValueDef(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - _, err = expect(parser, TokenKind[COLON]) + _, err = expect(parser, lexer.TokenKind[lexer.COLON]) if err != nil { return nil, err } @@ -831,17 +836,17 @@ func parseInputValueDef(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - var defaultValue Value - if skip(parser, TokenKind[EQUALS]) { + var defaultValue ast.Value + if skip(parser, lexer.TokenKind[lexer.EQUALS]) { val, err := parseConstValue(parser) if err != nil { return nil, err } - if val, ok := val.(Value); ok { + if val, ok := val.(ast.Value); ok { defaultValue = val } } - return NewAstInputValueDefinition(&AstInputValueDefinition{ + return ast.NewInputValueDefinition(&ast.InputValueDefinition{ Name: name, Type: ttype, DefaultValue: defaultValue, @@ -849,7 +854,7 @@ func parseInputValueDef(parser *Parser) (interface{}, error) { }), nil } -func parseInterfaceTypeDefinition(parser *Parser) (*AstInterfaceDefinition, error) { +func parseInterfaceTypeDefinition(parser *Parser) (*ast.InterfaceDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "interface") if err != nil { @@ -859,24 +864,24 @@ func parseInterfaceTypeDefinition(parser *Parser) (*AstInterfaceDefinition, erro if err != nil { return nil, err } - iFields, err := any(parser, TokenKind[BRACE_L], parseFieldDefinition, TokenKind[BRACE_R]) + iFields, err := any(parser, lexer.TokenKind[lexer.BRACE_L], parseFieldDefinition, lexer.TokenKind[lexer.BRACE_R]) if err != nil { return nil, err } - fields := []*AstFieldDefinition{} + fields := []*ast.FieldDefinition{} for _, iField := range iFields { if iField != nil { - fields = append(fields, iField.(*AstFieldDefinition)) + fields = append(fields, iField.(*ast.FieldDefinition)) } } - return NewAstInterfaceDefinition(&AstInterfaceDefinition{ + return ast.NewInterfaceDefinition(&ast.InterfaceDefinition{ Name: name, Loc: loc(parser, start), Fields: fields, }), nil } -func parseUnionTypeDefinition(parser *Parser) (*AstUnionDefinition, error) { +func parseUnionTypeDefinition(parser *Parser) (*ast.UnionDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "union") if err != nil { @@ -886,7 +891,7 @@ func parseUnionTypeDefinition(parser *Parser) (*AstUnionDefinition, error) { if err != nil { return nil, err } - _, err = expect(parser, TokenKind[EQUALS]) + _, err = expect(parser, lexer.TokenKind[lexer.EQUALS]) if err != nil { return nil, err } @@ -894,29 +899,29 @@ func parseUnionTypeDefinition(parser *Parser) (*AstUnionDefinition, error) { if err != nil { return nil, err } - return NewAstUnionDefinition(&AstUnionDefinition{ + return ast.NewUnionDefinition(&ast.UnionDefinition{ Name: name, Loc: loc(parser, start), Types: types, }), nil } -func parseUnionMembers(parser *Parser) ([]*AstNamed, error) { - members := []*AstNamed{} +func parseUnionMembers(parser *Parser) ([]*ast.Named, error) { + members := []*ast.Named{} for { member, err := parseNamed(parser) if err != nil { return members, err } members = append(members, member) - if !skip(parser, TokenKind[PIPE]) { + if !skip(parser, lexer.TokenKind[lexer.PIPE]) { break } } return members, nil } -func parseScalarTypeDefinition(parser *Parser) (*AstScalarDefinition, error) { +func parseScalarTypeDefinition(parser *Parser) (*ast.ScalarDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "scalar") if err != nil { @@ -926,14 +931,14 @@ func parseScalarTypeDefinition(parser *Parser) (*AstScalarDefinition, error) { if err != nil { return nil, err } - def := NewAstScalarDefinition(&AstScalarDefinition{ + def := ast.NewScalarDefinition(&ast.ScalarDefinition{ Name: name, Loc: loc(parser, start), }) return def, nil } -func parseEnumTypeDefinition(parser *Parser) (*AstEnumDefinition, error) { +func parseEnumTypeDefinition(parser *Parser) (*ast.EnumDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "enum") if err != nil { @@ -943,17 +948,17 @@ func parseEnumTypeDefinition(parser *Parser) (*AstEnumDefinition, error) { if err != nil { return nil, err } - iEnumValueDefs, err := any(parser, TokenKind[BRACE_L], parseEnumValueDefinition, TokenKind[BRACE_R]) + iEnumValueDefs, err := any(parser, lexer.TokenKind[lexer.BRACE_L], parseEnumValueDefinition, lexer.TokenKind[lexer.BRACE_R]) if err != nil { return nil, err } - values := []*AstEnumValueDefinition{} + values := []*ast.EnumValueDefinition{} for _, iEnumValueDef := range iEnumValueDefs { if iEnumValueDef != nil { - values = append(values, iEnumValueDef.(*AstEnumValueDefinition)) + values = append(values, iEnumValueDef.(*ast.EnumValueDefinition)) } } - return NewAstEnumDefinition(&AstEnumDefinition{ + return ast.NewEnumDefinition(&ast.EnumDefinition{ Name: name, Loc: loc(parser, start), Values: values, @@ -966,13 +971,13 @@ func parseEnumValueDefinition(parser *Parser) (interface{}, error) { if err != nil { return nil, err } - return NewAstEnumValueDefinition(&AstEnumValueDefinition{ + return ast.NewEnumValueDefinition(&ast.EnumValueDefinition{ Name: name, Loc: loc(parser, start), }), nil } -func parseInputObjectTypeDefinition(parser *Parser) (*AstInputObjectDefinition, error) { +func parseInputObjectTypeDefinition(parser *Parser) (*ast.InputObjectDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "input") if err != nil { @@ -982,24 +987,24 @@ func parseInputObjectTypeDefinition(parser *Parser) (*AstInputObjectDefinition, if err != nil { return nil, err } - iInputValueDefinitions, err := any(parser, TokenKind[BRACE_L], parseInputValueDef, TokenKind[BRACE_R]) + iInputValueDefinitions, err := any(parser, lexer.TokenKind[lexer.BRACE_L], parseInputValueDef, lexer.TokenKind[lexer.BRACE_R]) if err != nil { return nil, err } - fields := []*AstInputValueDefinition{} + fields := []*ast.InputValueDefinition{} for _, iInputValueDefinition := range iInputValueDefinitions { if iInputValueDefinition != nil { - fields = append(fields, iInputValueDefinition.(*AstInputValueDefinition)) + fields = append(fields, iInputValueDefinition.(*ast.InputValueDefinition)) } } - return NewAstInputObjectDefinition(&AstInputObjectDefinition{ + return ast.NewInputObjectDefinition(&ast.InputObjectDefinition{ Name: name, Loc: loc(parser, start), Fields: fields, }), nil } -func parseTypeExtensionDefinition(parser *Parser) (*AstTypeExtensionDefinition, error) { +func parseTypeExtensionDefinition(parser *Parser) (*ast.TypeExtensionDefinition, error) { start := parser.Token.Start _, err := expectKeyWord(parser, "extend") if err != nil { @@ -1010,7 +1015,7 @@ func parseTypeExtensionDefinition(parser *Parser) (*AstTypeExtensionDefinition, if err != nil { return nil, err } - return NewAstTypeExtensionDefinition(&AstTypeExtensionDefinition{ + return ast.NewTypeExtensionDefinition(&ast.TypeExtensionDefinition{ Loc: loc(parser, start), Definition: definition, }), nil @@ -1020,17 +1025,17 @@ func parseTypeExtensionDefinition(parser *Parser) (*AstTypeExtensionDefinition, // Returns a location object, used to identify the place in // the source that created a given parsed object. -func loc(parser *Parser, start int) *AstLocation { +func loc(parser *Parser, start int) *ast.Location { if parser.Options.NoLocation { return nil } if parser.Options.NoSource { - return NewAstLocation(&AstLocation{ + return ast.NewLocation(&ast.Location{ Start: start, End: parser.PrevEnd, }) } - return NewAstLocation(&AstLocation{ + return ast.NewLocation(&ast.Location{ Start: start, End: parser.PrevEnd, Source: parser.Source, @@ -1067,39 +1072,39 @@ func skip(parser *Parser, Kind int) bool { // If the next token is of the given kind, return that token after advancing // the parser. Otherwise, do not change the parser state and return false. -func expect(parser *Parser, kind int) (Token, error) { +func expect(parser *Parser, kind int) (lexer.Token, error) { token := parser.Token if token.Kind == kind { advance(parser) return token, nil } - descp := fmt.Sprintf("Expected %s, found %s", GetTokenKindDesc(kind), GetTokenDesc(token)) - return token, NewSyntaxError(parser.Source, token.Start, descp) + descp := fmt.Sprintf("Expected %s, found %s", lexer.GetTokenKindDesc(kind), lexer.GetTokenDesc(token)) + return token, gqlerrors.NewSyntaxError(parser.Source, token.Start, descp) } // If the next token is a keyword with the given value, return that token after // advancing the parser. Otherwise, do not change the parser state and return false. -func expectKeyWord(parser *Parser, value string) (Token, error) { +func expectKeyWord(parser *Parser, value string) (lexer.Token, error) { token := parser.Token - if token.Kind == TokenKind[NAME] && token.Value == value { + if token.Kind == lexer.TokenKind[lexer.NAME] && token.Value == value { advance(parser) return token, nil } - descp := fmt.Sprintf("Expected \"%s\", found %s", value, GetTokenDesc(token)) - return token, NewSyntaxError(parser.Source, token.Start, descp) + descp := fmt.Sprintf("Expected \"%s\", found %s", value, lexer.GetTokenDesc(token)) + return token, gqlerrors.NewSyntaxError(parser.Source, token.Start, descp) } // Helper function for creating an error when an unexpected lexed token // is encountered. -func unexpected(parser *Parser, atToken Token) error { - var token Token - if (atToken == Token{}) { +func unexpected(parser *Parser, atToken lexer.Token) error { + var token lexer.Token + if (atToken == lexer.Token{}) { token = parser.Token } else { token = parser.Token } - description := fmt.Sprintf("Unexpected %v", GetTokenDesc(token)) - return NewSyntaxError(parser.Source, token.Start, description) + description := fmt.Sprintf("Unexpected %v", lexer.GetTokenDesc(token)) + return gqlerrors.NewSyntaxError(parser.Source, token.Start, description) } // Returns a possibly empty list of parse nodes, determined by diff --git a/parser_test.go b/parser_test.go index 8f97a2e9..fdd2c3cc 100644 --- a/parser_test.go +++ b/parser_test.go @@ -6,6 +6,11 @@ import ( "reflect" "strings" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/language/source" ) func TestAcceptsOptionToNotIncludeSource(t *testing.T) { @@ -20,42 +25,42 @@ func TestAcceptsOptionToNotIncludeSource(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - oDef := AstOperationDefinition{ + oDef := ast.OperationDefinition{ Kind: "OperationDefinition", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 0, End: 9, }, Operation: "query", - Directives: []*AstDirective{}, - SelectionSet: &AstSelectionSet{ + Directives: []*ast.Directive{}, + SelectionSet: &ast.SelectionSet{ Kind: "SelectionSet", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 0, End: 9, }, - Selections: []Selection{ - &AstField{ + Selections: []ast.Selection{ + &ast.Field{ Kind: "Field", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 2, End: 7, }, - Name: &AstName{ + Name: &ast.Name{ Kind: "Name", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 2, End: 7, }, Value: "field", }, - Arguments: []*AstArgument{}, - Directives: []*AstDirective{}, + Arguments: []*ast.Argument{}, + Directives: []*ast.Directive{}, }, }, }, } - expectedDocument := NewAstDocument(&AstDocument{ - Loc: &AstLocation{ + expectedDocument := ast.NewDocument(&ast.Document{ + Loc: &ast.Location{ Start: 0, End: 9, }, - Definitions: []Node{&oDef}, + Definitions: []ast.Node{&oDef}, }) if !reflect.DeepEqual(document, expectedDocument) { t.Fatalf("unexpected document, expected: %v, got: %v", expectedDocument, document) @@ -72,14 +77,14 @@ func TestParseProvidesUsefulErrors(t *testing.T) { } _, err := Parse(params) - expectedError := &Error{ + expectedError := &gqlerrors.Error{ Message: `Syntax Error GraphQL (1:2) Expected Name, found EOF 1: { ^ `, Positions: []int{1}, - Locations: []SourceLocation{{1, 2}}, + Locations: []location.SourceLocation{{1, 2}}, } checkError(t, err, expectedError) @@ -119,7 +124,7 @@ fragment MissingOn Type func TestParseProvidesUsefulErrorsWhenUsingSource(t *testing.T) { test := errorMessageTest{ - NewSource(&Source{Body: "query", Name: "MyQuery.graphql"}), + source.NewSource(&source.Source{Body: "query", Name: "MyQuery.graphql"}), `Syntax Error MyQuery.graphql (1:6) Expected Name, found EOF`, false, } @@ -242,7 +247,7 @@ func TestParseCreatesAst(t *testing.T) { } } ` - source := NewSource(&Source{Body: body}) + source := source.NewSource(&source.Source{Body: body}) document, err := Parse( ParseParams{ Source: source, @@ -255,90 +260,90 @@ func TestParseCreatesAst(t *testing.T) { t.Fatalf("unexpected error: %v", err) } - oDef := AstOperationDefinition{ + oDef := ast.OperationDefinition{ Kind: "OperationDefinition", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 0, End: 40, }, Operation: "query", - Directives: []*AstDirective{}, - SelectionSet: &AstSelectionSet{ + Directives: []*ast.Directive{}, + SelectionSet: &ast.SelectionSet{ Kind: "SelectionSet", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 0, End: 40, }, - Selections: []Selection{ - &AstField{ + Selections: []ast.Selection{ + &ast.Field{ Kind: "Field", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 4, End: 38, }, - Name: &AstName{ + Name: &ast.Name{ Kind: "Name", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 4, End: 8, }, Value: "node", }, - Arguments: []*AstArgument{ + Arguments: []*ast.Argument{ { Kind: "Argument", - Name: &AstName{ + Name: &ast.Name{ Kind: "Name", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 9, End: 11, }, Value: "id", }, - Value: &AstIntValue{ + Value: &ast.IntValue{ Kind: "IntValue", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 13, End: 14, }, Value: "4", }, - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 9, End: 14, }, }, }, - Directives: []*AstDirective{}, - SelectionSet: &AstSelectionSet{ + Directives: []*ast.Directive{}, + SelectionSet: &ast.SelectionSet{ Kind: "SelectionSet", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 16, End: 38, }, - Selections: []Selection{ - &AstField{ + Selections: []ast.Selection{ + &ast.Field{ Kind: "Field", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 22, End: 24, }, - Name: &AstName{ + Name: &ast.Name{ Kind: "Name", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 22, End: 24, }, Value: "id", }, - Arguments: []*AstArgument{}, - Directives: []*AstDirective{}, + Arguments: []*ast.Argument{}, + Directives: []*ast.Directive{}, SelectionSet: nil, }, - &AstField{ + &ast.Field{ Kind: "Field", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 30, End: 34, }, - Name: &AstName{ + Name: &ast.Name{ Kind: "Name", - Loc: &AstLocation{ + Loc: &ast.Location{ Start: 30, End: 34, }, Value: "name", }, - Arguments: []*AstArgument{}, - Directives: []*AstDirective{}, + Arguments: []*ast.Argument{}, + Directives: []*ast.Directive{}, SelectionSet: nil, }, }, @@ -347,11 +352,11 @@ func TestParseCreatesAst(t *testing.T) { }, }, } - expectedDocument := NewAstDocument(&AstDocument{ - Loc: &AstLocation{ + expectedDocument := ast.NewDocument(&ast.Document{ + Loc: &ast.Location{ Start: 0, End: 41, }, - Definitions: []Node{&oDef}, + Definitions: []ast.Node{&oDef}, }) if !reflect.DeepEqual(document, expectedDocument) { t.Fatalf("unexpected document, expected: %v, got: %v", expectedDocument, document.Definitions) @@ -373,7 +378,7 @@ func testErrorMessage(t *testing.T, test errorMessageTest) { checkErrorMessage(t, err, test.expectedMessage) } -func checkError(t *testing.T, err error, expectedError *Error) { +func checkError(t *testing.T, err error, expectedError *gqlerrors.Error) { if expectedError == nil { if err != nil { t.Fatalf("unexpected error: %v", err) @@ -412,12 +417,12 @@ func checkErrorMessage(t *testing.T, err error, expectedMessage string) { } } -func toError(err error) *Error { +func toError(err error) *gqlerrors.Error { if err == nil { return nil } switch err := err.(type) { - case *Error: + case *gqlerrors.Error: return err default: return nil diff --git a/scalars.go b/scalars.go index f42b5b37..98dd67d7 100644 --- a/scalars.go +++ b/scalars.go @@ -3,6 +3,8 @@ package graphql import ( "fmt" "strconv" + + "github.com/chris-ramon/graphql/language/ast" ) var ( @@ -47,9 +49,9 @@ var Int *Scalar = NewScalar(ScalarConfig{ Name: "Int", Serialize: coerceInt, ParseValue: coerceInt, - ParseLiteral: func(valueAST Value) interface{} { + ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { - case *AstIntValue: + case *ast.IntValue: if intValue, err := strconv.Atoi(valueAST.Value); err == nil { return intValue } @@ -85,13 +87,13 @@ var Float *Scalar = NewScalar(ScalarConfig{ Name: "Float", Serialize: coerceFloat32, ParseValue: coerceFloat32, - ParseLiteral: func(valueAST Value) interface{} { + ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { - case *AstFloatValue: + case *ast.FloatValue: if floatValue, err := strconv.ParseFloat(valueAST.Value, 32); err == nil { return floatValue } - case *AstIntValue: + case *ast.IntValue: if floatValue, err := strconv.ParseFloat(valueAST.Value, 32); err == nil { return floatValue } @@ -108,9 +110,9 @@ var String *Scalar = NewScalar(ScalarConfig{ Name: "String", Serialize: coerceString, ParseValue: coerceString, - ParseLiteral: func(valueAST Value) interface{} { + ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { - case *AstStringValue: + case *ast.StringValue: return valueAST.Value } return "" @@ -150,9 +152,9 @@ var Boolean *Scalar = NewScalar(ScalarConfig{ Name: "Boolean", Serialize: coerceBool, ParseValue: coerceBool, - ParseLiteral: func(valueAST Value) interface{} { + ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { - case *AstBooleanValue: + case *ast.BooleanValue: return valueAST.Value } return false @@ -163,11 +165,11 @@ var ID *Scalar = NewScalar(ScalarConfig{ Name: "ID", Serialize: coerceString, ParseValue: coerceString, - ParseLiteral: func(valueAST Value) interface{} { + ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { - case *AstIntValue: + case *ast.IntValue: return valueAST.Value - case *AstStringValue: + case *ast.StringValue: return valueAST.Value } return "" diff --git a/schema_parser_test.go b/schema_parser_test.go index 75525134..5253ebc2 100644 --- a/schema_parser_test.go +++ b/schema_parser_test.go @@ -3,9 +3,14 @@ package graphql import ( "reflect" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql/language/source" ) -func parsee(t *testing.T, query string) *AstDocument { +func parse(t *testing.T, query string) *ast.Document { astDoc, err := Parse(ParseParams{ Source: query, Options: ParseOptions{ @@ -19,8 +24,8 @@ func parsee(t *testing.T, query string) *AstDocument { return astDoc } -func testLoc(start int, end int) *AstLocation { - return &AstLocation{ +func testLoc(start int, end int) *ast.Location { + return &ast.Location{ Start: start, End: end, } } @@ -30,28 +35,28 @@ func TestSchemaParser_SimpleType(t *testing.T) { type Hello { world: String }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(1, 31), - Definitions: []Node{ - NewAstObjectDefinition(&AstObjectDefinition{ + Definitions: []ast.Node{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: testLoc(1, 31), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(6, 11), }), - Interfaces: []*AstNamed{}, - Fields: []*AstFieldDefinition{ - NewAstFieldDefinition(&AstFieldDefinition{ + Interfaces: []*ast.Named{}, + Fields: []*ast.FieldDefinition{ + ast.NewFieldDefinition(&ast.FieldDefinition{ Loc: testLoc(16, 29), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "world", Loc: testLoc(16, 21), }), - Arguments: []*AstInputValueDefinition{}, - Type: NewAstNamed(&AstNamed{ + Arguments: []*ast.InputValueDefinition{}, + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(23, 29), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(23, 29), }), @@ -72,30 +77,30 @@ func TestSchemaParser_SimpleExtension(t *testing.T) { extend type Hello { world: String }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(1, 38), - Definitions: []Node{ - NewAstTypeExtensionDefinition(&AstTypeExtensionDefinition{ + Definitions: []ast.Node{ + ast.NewTypeExtensionDefinition(&ast.TypeExtensionDefinition{ Loc: testLoc(1, 38), - Definition: NewAstObjectDefinition(&AstObjectDefinition{ + Definition: ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: testLoc(8, 38), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(13, 18), }), - Interfaces: []*AstNamed{}, - Fields: []*AstFieldDefinition{ - NewAstFieldDefinition(&AstFieldDefinition{ + Interfaces: []*ast.Named{}, + Fields: []*ast.FieldDefinition{ + ast.NewFieldDefinition(&ast.FieldDefinition{ Loc: testLoc(23, 36), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "world", Loc: testLoc(23, 28), }), - Arguments: []*AstInputValueDefinition{}, - Type: NewAstNamed(&AstNamed{ + Arguments: []*ast.InputValueDefinition{}, + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(30, 36), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(30, 36), }), @@ -117,31 +122,31 @@ func TestSchemaParser_SimpleNonNullType(t *testing.T) { type Hello { world: String! }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(1, 32), - Definitions: []Node{ - NewAstObjectDefinition(&AstObjectDefinition{ + Definitions: []ast.Node{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: testLoc(1, 32), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(6, 11), }), - Interfaces: []*AstNamed{}, - Fields: []*AstFieldDefinition{ - NewAstFieldDefinition(&AstFieldDefinition{ + Interfaces: []*ast.Named{}, + Fields: []*ast.FieldDefinition{ + ast.NewFieldDefinition(&ast.FieldDefinition{ Loc: testLoc(16, 30), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "world", Loc: testLoc(16, 21), }), - Arguments: []*AstInputValueDefinition{}, - Type: NewAstNonNull(&AstNonNull{ + Arguments: []*ast.InputValueDefinition{}, + Type: ast.NewNonNull(&ast.NonNull{ Kind: "NonNullType", Loc: testLoc(23, 30), - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(23, 29), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(23, 29), }), @@ -159,26 +164,26 @@ type Hello { func TestSchemaParser_SimpleTypeInheritingInterface(t *testing.T) { body := `type Hello implements World { }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(0, 31), - Definitions: []Node{ - NewAstObjectDefinition(&AstObjectDefinition{ + Definitions: []ast.Node{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: testLoc(0, 31), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(5, 10), }), - Interfaces: []*AstNamed{ - NewAstNamed(&AstNamed{ - Name: NewAstName(&AstName{ + Interfaces: []*ast.Named{ + ast.NewNamed(&ast.Named{ + Name: ast.NewName(&ast.Name{ Value: "World", Loc: testLoc(22, 27), }), Loc: testLoc(22, 27), }), }, - Fields: []*AstFieldDefinition{}, + Fields: []*ast.FieldDefinition{}, }), }, }) @@ -189,33 +194,33 @@ func TestSchemaParser_SimpleTypeInheritingInterface(t *testing.T) { func TestSchemaParser_SimpleTypeInheritingMultipleInterfaces(t *testing.T) { body := `type Hello implements Wo, rld { }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(0, 33), - Definitions: []Node{ - NewAstObjectDefinition(&AstObjectDefinition{ + Definitions: []ast.Node{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: testLoc(0, 33), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(5, 10), }), - Interfaces: []*AstNamed{ - NewAstNamed(&AstNamed{ - Name: NewAstName(&AstName{ + Interfaces: []*ast.Named{ + ast.NewNamed(&ast.Named{ + Name: ast.NewName(&ast.Name{ Value: "Wo", Loc: testLoc(22, 24), }), Loc: testLoc(22, 24), }), - NewAstNamed(&AstNamed{ - Name: NewAstName(&AstName{ + ast.NewNamed(&ast.Named{ + Name: ast.NewName(&ast.Name{ Value: "rld", Loc: testLoc(26, 29), }), Loc: testLoc(26, 29), }), }, - Fields: []*AstFieldDefinition{}, + Fields: []*ast.FieldDefinition{}, }), }, }) @@ -226,19 +231,19 @@ func TestSchemaParser_SimpleTypeInheritingMultipleInterfaces(t *testing.T) { func TestSchemaParser_SingleValueEnum(t *testing.T) { body := `enum Hello { WORLD }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(0, 20), - Definitions: []Node{ - NewAstEnumDefinition(&AstEnumDefinition{ + Definitions: []ast.Node{ + ast.NewEnumDefinition(&ast.EnumDefinition{ Loc: testLoc(0, 20), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(5, 10), }), - Values: []*AstEnumValueDefinition{ - NewAstEnumValueDefinition(&AstEnumValueDefinition{ - Name: NewAstName(&AstName{ + Values: []*ast.EnumValueDefinition{ + ast.NewEnumValueDefinition(&ast.EnumValueDefinition{ + Name: ast.NewName(&ast.Name{ Value: "WORLD", Loc: testLoc(13, 18), }), @@ -255,26 +260,26 @@ func TestSchemaParser_SingleValueEnum(t *testing.T) { func TestSchemaParser_DoubleValueEnum(t *testing.T) { body := `enum Hello { WO, RLD }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(0, 22), - Definitions: []Node{ - NewAstEnumDefinition(&AstEnumDefinition{ + Definitions: []ast.Node{ + ast.NewEnumDefinition(&ast.EnumDefinition{ Loc: testLoc(0, 22), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(5, 10), }), - Values: []*AstEnumValueDefinition{ - NewAstEnumValueDefinition(&AstEnumValueDefinition{ - Name: NewAstName(&AstName{ + Values: []*ast.EnumValueDefinition{ + ast.NewEnumValueDefinition(&ast.EnumValueDefinition{ + Name: ast.NewName(&ast.Name{ Value: "WO", Loc: testLoc(13, 15), }), Loc: testLoc(13, 15), }), - NewAstEnumValueDefinition(&AstEnumValueDefinition{ - Name: NewAstName(&AstName{ + ast.NewEnumValueDefinition(&ast.EnumValueDefinition{ + Name: ast.NewName(&ast.Name{ Value: "RLD", Loc: testLoc(17, 20), }), @@ -294,27 +299,27 @@ func TestSchemaParser_SimpleInterface(t *testing.T) { interface Hello { world: String }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(1, 36), - Definitions: []Node{ - NewAstInterfaceDefinition(&AstInterfaceDefinition{ + Definitions: []ast.Node{ + ast.NewInterfaceDefinition(&ast.InterfaceDefinition{ Loc: testLoc(1, 36), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(11, 16), }), - Fields: []*AstFieldDefinition{ - NewAstFieldDefinition(&AstFieldDefinition{ + Fields: []*ast.FieldDefinition{ + ast.NewFieldDefinition(&ast.FieldDefinition{ Loc: testLoc(21, 34), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "world", Loc: testLoc(21, 26), }), - Arguments: []*AstInputValueDefinition{}, - Type: NewAstNamed(&AstNamed{ + Arguments: []*ast.InputValueDefinition{}, + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(28, 34), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(28, 34), }), @@ -334,34 +339,34 @@ func TestSchemaParser_SimpleFieldWithArg(t *testing.T) { type Hello { world(flag: Boolean): String }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(1, 46), - Definitions: []Node{ - NewAstObjectDefinition(&AstObjectDefinition{ + Definitions: []ast.Node{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: testLoc(1, 46), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(6, 11), }), - Interfaces: []*AstNamed{}, - Fields: []*AstFieldDefinition{ - NewAstFieldDefinition(&AstFieldDefinition{ + Interfaces: []*ast.Named{}, + Fields: []*ast.FieldDefinition{ + ast.NewFieldDefinition(&ast.FieldDefinition{ Loc: testLoc(16, 44), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "world", Loc: testLoc(16, 21), }), - Arguments: []*AstInputValueDefinition{ - NewAstInputValueDefinition(&AstInputValueDefinition{ + Arguments: []*ast.InputValueDefinition{ + ast.NewInputValueDefinition(&ast.InputValueDefinition{ Loc: testLoc(22, 35), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "flag", Loc: testLoc(22, 26), }), - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(28, 35), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Boolean", Loc: testLoc(28, 35), }), @@ -369,9 +374,9 @@ type Hello { DefaultValue: nil, }), }, - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(38, 44), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(38, 44), }), @@ -391,47 +396,47 @@ func TestSchemaParser_SimpleFieldWithArgWithDefaultValue(t *testing.T) { type Hello { world(flag: Boolean = true): String }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(1, 53), - Definitions: []Node{ - NewAstObjectDefinition(&AstObjectDefinition{ + Definitions: []ast.Node{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: testLoc(1, 53), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(6, 11), }), - Interfaces: []*AstNamed{}, - Fields: []*AstFieldDefinition{ - NewAstFieldDefinition(&AstFieldDefinition{ + Interfaces: []*ast.Named{}, + Fields: []*ast.FieldDefinition{ + ast.NewFieldDefinition(&ast.FieldDefinition{ Loc: testLoc(16, 51), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "world", Loc: testLoc(16, 21), }), - Arguments: []*AstInputValueDefinition{ - NewAstInputValueDefinition(&AstInputValueDefinition{ + Arguments: []*ast.InputValueDefinition{ + ast.NewInputValueDefinition(&ast.InputValueDefinition{ Loc: testLoc(22, 42), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "flag", Loc: testLoc(22, 26), }), - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(28, 35), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Boolean", Loc: testLoc(28, 35), }), }), - DefaultValue: NewAstBooleanValue(&AstBooleanValue{ + DefaultValue: ast.NewBooleanValue(&ast.BooleanValue{ Value: true, Loc: testLoc(38, 42), }), }), }, - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(45, 51), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(45, 51), }), @@ -451,36 +456,36 @@ func TestSchemaParser_SimpleFieldWithListArg(t *testing.T) { type Hello { world(things: [String]): String }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(1, 49), - Definitions: []Node{ - NewAstObjectDefinition(&AstObjectDefinition{ + Definitions: []ast.Node{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: testLoc(1, 49), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(6, 11), }), - Interfaces: []*AstNamed{}, - Fields: []*AstFieldDefinition{ - NewAstFieldDefinition(&AstFieldDefinition{ + Interfaces: []*ast.Named{}, + Fields: []*ast.FieldDefinition{ + ast.NewFieldDefinition(&ast.FieldDefinition{ Loc: testLoc(16, 47), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "world", Loc: testLoc(16, 21), }), - Arguments: []*AstInputValueDefinition{ - NewAstInputValueDefinition(&AstInputValueDefinition{ + Arguments: []*ast.InputValueDefinition{ + ast.NewInputValueDefinition(&ast.InputValueDefinition{ Loc: testLoc(22, 38), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "things", Loc: testLoc(22, 28), }), - Type: NewAstList(&AstList{ + Type: ast.NewList(&ast.List{ Loc: testLoc(30, 38), - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(31, 37), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(31, 37), }), @@ -489,9 +494,9 @@ type Hello { DefaultValue: nil, }), }, - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(41, 47), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(41, 47), }), @@ -511,49 +516,49 @@ func TestSchemaParser_SimpleFieldWithTwoArg(t *testing.T) { type Hello { world(argOne: Boolean, argTwo: Int): String }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(1, 61), - Definitions: []Node{ - NewAstObjectDefinition(&AstObjectDefinition{ + Definitions: []ast.Node{ + ast.NewObjectDefinition(&ast.ObjectDefinition{ Loc: testLoc(1, 61), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(6, 11), }), - Interfaces: []*AstNamed{}, - Fields: []*AstFieldDefinition{ - NewAstFieldDefinition(&AstFieldDefinition{ + Interfaces: []*ast.Named{}, + Fields: []*ast.FieldDefinition{ + ast.NewFieldDefinition(&ast.FieldDefinition{ Loc: testLoc(16, 59), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "world", Loc: testLoc(16, 21), }), - Arguments: []*AstInputValueDefinition{ - NewAstInputValueDefinition(&AstInputValueDefinition{ + Arguments: []*ast.InputValueDefinition{ + ast.NewInputValueDefinition(&ast.InputValueDefinition{ Loc: testLoc(22, 37), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "argOne", Loc: testLoc(22, 28), }), - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(30, 37), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Boolean", Loc: testLoc(30, 37), }), }), DefaultValue: nil, }), - NewAstInputValueDefinition(&AstInputValueDefinition{ + ast.NewInputValueDefinition(&ast.InputValueDefinition{ Loc: testLoc(39, 50), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "argTwo", Loc: testLoc(39, 45), }), - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(47, 50), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Int", Loc: testLoc(47, 50), }), @@ -561,9 +566,9 @@ type Hello { DefaultValue: nil, }), }, - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(53, 59), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(53, 59), }), @@ -580,20 +585,20 @@ type Hello { func TestSchemaParser_SimpleUnion(t *testing.T) { body := `union Hello = World` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(0, 19), - Definitions: []Node{ - NewAstUnionDefinition(&AstUnionDefinition{ + Definitions: []ast.Node{ + ast.NewUnionDefinition(&ast.UnionDefinition{ Loc: testLoc(0, 19), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(6, 11), }), - Types: []*AstNamed{ - NewAstNamed(&AstNamed{ + Types: []*ast.Named{ + ast.NewNamed(&ast.Named{ Loc: testLoc(14, 19), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "World", Loc: testLoc(14, 19), }), @@ -609,27 +614,27 @@ func TestSchemaParser_SimpleUnion(t *testing.T) { func TestSchemaParser_UnionWithTwoTypes(t *testing.T) { body := `union Hello = Wo | Rld` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(0, 22), - Definitions: []Node{ - NewAstUnionDefinition(&AstUnionDefinition{ + Definitions: []ast.Node{ + ast.NewUnionDefinition(&ast.UnionDefinition{ Loc: testLoc(0, 22), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(6, 11), }), - Types: []*AstNamed{ - NewAstNamed(&AstNamed{ + Types: []*ast.Named{ + ast.NewNamed(&ast.Named{ Loc: testLoc(14, 16), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Wo", Loc: testLoc(14, 16), }), }), - NewAstNamed(&AstNamed{ + ast.NewNamed(&ast.Named{ Loc: testLoc(19, 22), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Rld", Loc: testLoc(19, 22), }), @@ -645,13 +650,13 @@ func TestSchemaParser_UnionWithTwoTypes(t *testing.T) { func TestSchemaParser_Scalar(t *testing.T) { body := `scalar Hello` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(0, 12), - Definitions: []Node{ - NewAstScalarDefinition(&AstScalarDefinition{ + Definitions: []ast.Node{ + ast.NewScalarDefinition(&ast.ScalarDefinition{ Loc: testLoc(0, 12), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(7, 12), }), @@ -668,26 +673,26 @@ func TestSchemaParser_SimpleInputObject(t *testing.T) { input Hello { world: String }` - astDoc := parsee(t, body) - expected := NewAstDocument(&AstDocument{ + astDoc := parse(t, body) + expected := ast.NewDocument(&ast.Document{ Loc: testLoc(1, 32), - Definitions: []Node{ - NewAstInputObjectDefinition(&AstInputObjectDefinition{ + Definitions: []ast.Node{ + ast.NewInputObjectDefinition(&ast.InputObjectDefinition{ Loc: testLoc(1, 32), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "Hello", Loc: testLoc(7, 12), }), - Fields: []*AstInputValueDefinition{ - NewAstInputValueDefinition(&AstInputValueDefinition{ + Fields: []*ast.InputValueDefinition{ + ast.NewInputValueDefinition(&ast.InputValueDefinition{ Loc: testLoc(17, 30), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "world", Loc: testLoc(17, 22), }), - Type: NewAstNamed(&AstNamed{ + Type: ast.NewNamed(&ast.Named{ Loc: testLoc(24, 30), - Name: NewAstName(&AstName{ + Name: ast.NewName(&ast.Name{ Value: "String", Loc: testLoc(24, 30), }), @@ -717,7 +722,7 @@ input Hello { }, }) - expectedError := &Error{ + expectedError := &gqlerrors.Error{ Message: `Syntax Error GraphQL (3:8) Expected :, found ( 2: input Hello { @@ -732,8 +737,8 @@ input Hello { ^ 4: } `, - Nodes: []Node{}, - Source: &Source{ + Nodes: []ast.Node{}, + Source: &source.Source{ Body: ` input Hello { world(foo: Int): String @@ -741,7 +746,7 @@ input Hello { Name: "GraphQL", }, Positions: []int{22}, - Locations: []SourceLocation{ + Locations: []location.SourceLocation{ {Line: 3, Column: 8}, }, } diff --git a/testutil.go b/testutil.go index 17b3324f..0661f79e 100644 --- a/testutil.go +++ b/testutil.go @@ -6,6 +6,7 @@ import ( "strconv" "testing" + "github.com/chris-ramon/graphql/language/ast" "github.com/kr/pretty" ) @@ -340,7 +341,7 @@ func GetHero(episode interface{}) interface{} { // Test helper functions -func TestParse(t *testing.T, query string) *AstDocument { +func TestParse(t *testing.T, query string) *ast.Document { astDoc, err := Parse(ParseParams{ Source: query, Options: ParseOptions{ @@ -364,7 +365,7 @@ func Diff(a, b interface{}) []string { return pretty.Diff(a, b) } -func ASTToJSON(t *testing.T, a Node) interface{} { +func ASTToJSON(t *testing.T, a ast.Node) interface{} { b, err := json.Marshal(a) if err != nil { t.Fatalf("Failed to marshal Node %v", err) diff --git a/types.go b/types.go index 4d81df36..13df16fb 100644 --- a/types.go +++ b/types.go @@ -1,10 +1,14 @@ package graphql +import ( + "github.com/chris-ramon/graphql/gqlerrors" +) + // type Schema interface{} type Result struct { - Data interface{} `json:"data"` - Errors []FormattedError `json:"errors,omitempty"` + Data interface{} `json:"data"` + Errors []gqlerrors.FormattedError `json:"errors,omitempty"` } func (r *Result) HasErrors() bool { diff --git a/validation_test.go b/validation_test.go index 93b02de3..430b3490 100644 --- a/validation_test.go +++ b/validation_test.go @@ -2,6 +2,8 @@ package graphql import ( "testing" + + "github.com/chris-ramon/graphql/language/ast" ) var someScalarType = NewScalar(ScalarConfig{ @@ -12,7 +14,7 @@ var someScalarType = NewScalar(ScalarConfig{ ParseValue: func(value interface{}) interface{} { return nil }, - ParseLiteral: func(valueAST Value) interface{} { + ParseLiteral: func(valueAST ast.Value) interface{} { return nil }, }) @@ -850,7 +852,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_AcceptsAScalarTypeDefiningPars ParseValue: func(value interface{}) interface{} { return nil }, - ParseLiteral: func(valueAST Value) interface{} { + ParseLiteral: func(valueAST ast.Value) interface{} { return nil }, })) @@ -881,7 +883,7 @@ func TestTypeSystem_ScalarTypesMustBeSerializable_RejectsAScalarTypeDefiningPars Serialize: func(value interface{}) interface{} { return nil }, - ParseLiteral: func(valueAST Value) interface{} { + ParseLiteral: func(valueAST ast.Value) interface{} { return nil }, })) diff --git a/validator.go b/validator.go index cedcd934..24879e65 100644 --- a/validator.go +++ b/validator.go @@ -1,11 +1,16 @@ package graphql +import ( + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/ast" +) + type ValidationResult struct { IsValid bool - Errors []FormattedError + Errors []gqlerrors.FormattedError } -func ValidateDocument(schema Schema, ast *AstDocument) (vr ValidationResult) { +func ValidateDocument(schema Schema, ast *ast.Document) (vr ValidationResult) { vr.IsValid = true return vr } diff --git a/values.go b/values.go index 0080bb05..08d812b3 100644 --- a/values.go +++ b/values.go @@ -6,13 +6,16 @@ import ( "math" "reflect" - "github.com/chris-ramon/graphql/kinds" + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql/language/printer" ) // Prepares an object map of variableValues of the correct type based on the // provided variable definitions and arbitrary input. If the input cannot be // parsed to match the variable definitions, a GraphQLError will be returned. -func getVariableValues(schema Schema, definitionASTs []*AstVariableDefinition, inputs map[string]interface{}) (map[string]interface{}, error) { +func getVariableValues(schema Schema, definitionASTs []*ast.VariableDefinition, inputs map[string]interface{}) (map[string]interface{}, error) { values := map[string]interface{}{} for _, defAST := range definitionASTs { if defAST == nil || defAST.Variable == nil || defAST.Variable.Name == nil { @@ -30,9 +33,9 @@ func getVariableValues(schema Schema, definitionASTs []*AstVariableDefinition, i // Prepares an object map of argument values given a list of argument // definitions and list of argument AST nodes. -func getArgumentValues(argDefs []*Argument, argASTs []*AstArgument, variableVariables map[string]interface{}) (map[string]interface{}, error) { +func getArgumentValues(argDefs []*Argument, argASTs []*ast.Argument, variableVariables map[string]interface{}) (map[string]interface{}, error) { - argASTMap := map[string]*AstArgument{} + argASTMap := map[string]*ast.Argument{} for _, argAST := range argASTs { if argAST.Name != nil { argASTMap[argAST.Name.Value] = argAST @@ -42,7 +45,7 @@ func getArgumentValues(argDefs []*Argument, argASTs []*AstArgument, variableVari for _, argDef := range argDefs { name := argDef.Name - var valueAST Value + var valueAST ast.Value if argAST, ok := argASTMap[name]; ok { valueAST = argAST.Value } @@ -59,7 +62,7 @@ func getArgumentValues(argDefs []*Argument, argASTs []*AstArgument, variableVari // Given a variable definition, and any value of input, return a value which // adheres to the variable definition, or throw an error. -func getVariableValue(schema Schema, definitionAST *AstVariableDefinition, input interface{}) (interface{}, error) { +func getVariableValue(schema Schema, definitionAST *ast.VariableDefinition, input interface{}) (interface{}, error) { ttype, err := typeFromAST(schema, definitionAST.Type) if err != nil { return nil, err @@ -67,10 +70,10 @@ func getVariableValue(schema Schema, definitionAST *AstVariableDefinition, input variable := definitionAST.Variable if ttype == nil || !IsInputType(ttype) { - return "", NewError( + return "", gqlerrors.NewError( fmt.Sprintf(`Variable "$%v" expected value of type `+ - `"%v" which cannot be used as an input type.`, variable.Name.Value, Print(definitionAST.Type)), - []Node{definitionAST}, + `"%v" which cannot be used as an input type.`, variable.Name.Value, printer.Print(definitionAST.Type)), + []ast.Node{definitionAST}, "", nil, []int{}, @@ -89,10 +92,10 @@ func getVariableValue(schema Schema, definitionAST *AstVariableDefinition, input return coerceValue(ttype, input), nil } if isNullish(input) { - return "", NewError( + return "", gqlerrors.NewError( fmt.Sprintf(`Variable "$%v" of required type `+ - `"%v" was not provided.`, variable.Name.Value, Print(definitionAST.Type)), - []Node{definitionAST}, + `"%v" was not provided.`, variable.Name.Value, printer.Print(definitionAST.Type)), + []ast.Node{definitionAST}, "", nil, []int{}, @@ -103,10 +106,10 @@ func getVariableValue(schema Schema, definitionAST *AstVariableDefinition, input if err == nil { inputStr = string(b) } - return "", NewError( + return "", gqlerrors.NewError( fmt.Sprintf(`Variable "$%v" expected value of type `+ - `"%v" but got: %v.`, variable.Name.Value, Print(definitionAST.Type), inputStr), - []Node{definitionAST}, + `"%v" but got: %v.`, variable.Name.Value, printer.Print(definitionAST.Type), inputStr), + []ast.Node{definitionAST}, "", nil, []int{}, @@ -175,21 +178,21 @@ func coerceValue(ttype Input, value interface{}) interface{} { // graphql-js/src/utilities.js` // TODO: figure out where to organize utils -func typeFromAST(schema Schema, inputTypeAST AstType) (Type, error) { +func typeFromAST(schema Schema, inputTypeAST ast.Type) (Type, error) { switch inputTypeAST := inputTypeAST.(type) { - case *AstList: + case *ast.List: innerType, err := typeFromAST(schema, inputTypeAST.Type) if err != nil { return nil, err } return NewList(innerType), nil - case *AstNonNull: + case *ast.NonNull: innerType, err := typeFromAST(schema, inputTypeAST.Type) if err != nil { return nil, err } return NewNonNull(innerType), nil - case *AstNamed: + case *ast.Named: nameValue := "" if inputTypeAST.Name != nil { nameValue = inputTypeAST.Name.Value @@ -301,7 +304,7 @@ func isNullish(value interface{}) bool { * | Int / Float | Number | * */ -func valueFromAST(valueAST Value, ttype Input, variables map[string]interface{}) interface{} { +func valueFromAST(valueAST ast.Value, ttype Input, variables map[string]interface{}) interface{} { if ttype, ok := ttype.(*NonNull); ok { val := valueFromAST(valueAST, ttype.OfType, variables) @@ -312,7 +315,7 @@ func valueFromAST(valueAST Value, ttype Input, variables map[string]interface{}) return nil } - if valueAST, ok := valueAST.(*AstVariable); ok && valueAST.Kind == kinds.Variable { + if valueAST, ok := valueAST.(*ast.Variable); ok && valueAST.Kind == kinds.Variable { if valueAST.Name == nil { return nil } @@ -332,7 +335,7 @@ func valueFromAST(valueAST Value, ttype Input, variables map[string]interface{}) if ttype, ok := ttype.(*List); ok { itemType := ttype.OfType - if valueAST, ok := valueAST.(*AstListValue); ok && valueAST.Kind == kinds.ListValue { + if valueAST, ok := valueAST.(*ast.ListValue); ok && valueAST.Kind == kinds.ListValue { values := []interface{}{} for _, itemAST := range valueAST.Values { v := valueFromAST(itemAST, itemType, variables) @@ -345,11 +348,11 @@ func valueFromAST(valueAST Value, ttype Input, variables map[string]interface{}) } if ttype, ok := ttype.(*InputObject); ok { - valueAST, ok := valueAST.(*AstObjectValue) + valueAST, ok := valueAST.(*ast.ObjectValue) if !ok { return nil } - fieldASTs := map[string]*AstObjectField{} + fieldASTs := map[string]*ast.ObjectField{} for _, fieldAST := range valueAST.Fields { if fieldAST.Name == nil { continue @@ -392,7 +395,7 @@ func valueFromAST(valueAST Value, ttype Input, variables map[string]interface{}) func invariant(condition bool, message string) error { if !condition { - return NewFormattedError(message) + return gqlerrors.NewFormattedError(message) } return nil } diff --git a/variables_test.go b/variables_test.go index e9003531..f3b2f154 100644 --- a/variables_test.go +++ b/variables_test.go @@ -4,6 +4,10 @@ import ( "encoding/json" "reflect" "testing" + + "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql/language/location" ) var testComplexScalar *Scalar = NewScalar(ScalarConfig{ @@ -20,7 +24,7 @@ var testComplexScalar *Scalar = NewScalar(ScalarConfig{ } return nil }, - ParseLiteral: func(valueAST Value) interface{} { + ParseLiteral: func(valueAST ast.Value) interface{} { astValue := valueAST.GetValue() if astValue, ok := astValue.(string); ok && astValue == "SerializedValue" { return "DeserializedValue" @@ -224,7 +228,7 @@ func TestVariables_ObjectsAndNullability_UsingInlineStructs_DoesNotUseIncorrectV } } -func testVariables_ObjectsAndNullability_UsingVariables_GetAST(t *testing.T) *AstDocument { +func testVariables_ObjectsAndNullability_UsingVariables_GetAST(t *testing.T) *ast.Document { doc := ` query q($input: TestInputObject) { fieldWithObjectInput(input: $input) @@ -361,12 +365,12 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnNullForNestedNon } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: {"a":"foo","b":"bar","c":null}.`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, @@ -396,12 +400,12 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnIncorrectType(t } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: "foo bar".`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, @@ -434,12 +438,12 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnOmissionOfNested } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: {"a":"foo","b":"bar"}.`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, @@ -474,12 +478,12 @@ func TestVariables_ObjectsAndNullability_UsingVariables_ErrorsOnAdditionOfUnknow } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestInputObject" but ` + `got: {"a":"foo","b":"bar","c":"baz","d":"dog"}.`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, @@ -685,11 +689,11 @@ func TestVariables_NonNullableScalars_DoesNotAllowNonNullableInputsToBeOmittedIn expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$value" of required type "String!" was not provided.`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 31, }, }, @@ -724,11 +728,11 @@ func TestVariables_NonNullableScalars_DoesNotAllowNonNullableInputsToBeSetToNull } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$value" of required type "String!" was not provided.`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 31, }, }, @@ -952,11 +956,11 @@ func TestVariables_ListsAndNullability_DoesNotAllowNonNullListsToBeNull(t *testi ` expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" of required type "[String]!" was not provided.`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, @@ -1109,12 +1113,12 @@ func TestVariables_ListsAndNullability_DoesNotAllowListOfNonNullsToContainNull(t } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "[String!]" but got: ` + `["A",null,"B"].`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, @@ -1148,11 +1152,11 @@ func TestVariables_ListsAndNullability_DoesNotAllowNonNullListOfNonNullsToBeNull } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" of required type "[String!]!" was not provided.`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, @@ -1216,12 +1220,12 @@ func TestVariables_ListsAndNullability_DoesNotAllowNonNullListOfNonNullsToContai } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "[String!]!" but got: ` + `["A",null,"B"].`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, @@ -1257,11 +1261,11 @@ func TestVariables_ListsAndNullability_DoesNotAllowInvalidTypesToBeUsedAsValues( } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "TestType!" which cannot be used as an input type.`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, @@ -1295,11 +1299,11 @@ func TestVariables_ListsAndNullability_DoesNotAllowUnknownTypesToBeUsedAsValues( } expected := &Result{ Data: nil, - Errors: []FormattedError{ - FormattedError{ + Errors: []gqlerrors.FormattedError{ + gqlerrors.FormattedError{ Message: `Variable "$input" expected value of type "UnknownType!" which cannot be used as an input type.`, - Locations: []SourceLocation{ - SourceLocation{ + Locations: []location.SourceLocation{ + location.SourceLocation{ Line: 2, Column: 17, }, }, From 43c608830e714fc41cca6cf6113fd015dbf6786d Mon Sep 17 00:00:00 2001 From: Nathaniel Maman Date: Fri, 30 Oct 2015 00:53:29 +0200 Subject: [PATCH 6/6] rename the lib name to graph-go for fix travis err --- README.md | 2 +- abstract_test.go | 4 ++-- definition.go | 2 +- enum_type_test.go | 2 +- executor.go | 4 ++-- executor_test.go | 4 ++-- gqlerrors/error.go | 6 +++--- gqlerrors/formatted.go | 2 +- gqlerrors/located.go | 2 +- gqlerrors/syntax.go | 6 +++--- graphql.go | 4 ++-- introspection.go | 4 ++-- introspection_test.go | 4 ++-- language/ast/arguments.go | 2 +- language/ast/definitions.go | 2 +- language/ast/directives.go | 2 +- language/ast/document.go | 2 +- language/ast/location.go | 2 +- language/ast/name.go | 2 +- language/ast/selections.go | 2 +- language/ast/type_definitions.go | 2 +- language/ast/types.go | 2 +- language/ast/values.go | 2 +- language/lexer/lexer.go | 4 ++-- language/lexer/lexer_test.go | 2 +- language/location/location.go | 2 +- language/printer/printer.go | 4 ++-- language/visitor/visitor_test.go | 6 +++--- lists_test.go | 4 ++-- located.go | 4 ++-- mutations_test.go | 4 ++-- nonnull_test.go | 4 ++-- parser.go | 8 ++++---- parser_test.go | 8 ++++---- scalars.go | 2 +- schema_parser_test.go | 8 ++++---- testutil.go | 2 +- types.go | 2 +- validation_test.go | 2 +- validator.go | 4 ++-- values.go | 8 ++++---- variables_test.go | 6 +++--- 42 files changed, 75 insertions(+), 75 deletions(-) diff --git a/README.md b/README.md index f4a9b85b..22fc20d9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -graphql [![Build Status](https://travis-ci.org/chris-ramon/graphql.svg)](https://travis-ci.org/chris-ramon/graphql) [![GoDoc](https://godoc.org/graphql.co/graphql?status.svg)](https://godoc.org/github.com/chris-ramon/graphql) [![Coverage Status](https://coveralls.io/repos/chris-ramon/graphql/badge.svg?branch=master&service=github)](https://coveralls.io/github/chris-ramon/graphql?branch=master) +graphql [![Build Status](https://travis-ci.org/chris-ramon/graphql.svg)](https://travis-ci.org/chris-ramon/graphql) [![GoDoc](https://godoc.org/graphql.co/graphql?status.svg)](https://godoc.org/github.com/chris-ramon/graphql-go) [![Coverage Status](https://coveralls.io/repos/chris-ramon/graphql/badge.svg?branch=master&service=github)](https://coveralls.io/github/chris-ramon/graphql?branch=master) ===== An *work in progress* implementation of GraphQL for Go. diff --git a/abstract_test.go b/abstract_test.go index 98504b22..69a219ef 100644 --- a/abstract_test.go +++ b/abstract_test.go @@ -4,8 +4,8 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/location" ) type testDog struct { diff --git a/definition.go b/definition.go index c1f0b126..e10a5b36 100644 --- a/definition.go +++ b/definition.go @@ -6,7 +6,7 @@ import ( "reflect" "regexp" - "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql-go/language/ast" ) // These are all of the possible kinds of diff --git a/enum_type_test.go b/enum_type_test.go index b0198e75..80fbc5e3 100644 --- a/enum_type_test.go +++ b/enum_type_test.go @@ -4,7 +4,7 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql-go/gqlerrors" ) var enumTypeTestColorType = NewEnum(EnumConfig{ diff --git a/executor.go b/executor.go index e7014f58..b9f49998 100644 --- a/executor.go +++ b/executor.go @@ -5,8 +5,8 @@ import ( "reflect" "strings" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/ast" ) type ExecuteParams struct { diff --git a/executor_test.go b/executor_test.go index 7c8e5ba0..94350b71 100644 --- a/executor_test.go +++ b/executor_test.go @@ -6,8 +6,8 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/location" ) func TestExecutesArbitraryCode(t *testing.T) { diff --git a/gqlerrors/error.go b/gqlerrors/error.go index a6f59699..9722d19d 100644 --- a/gqlerrors/error.go +++ b/gqlerrors/error.go @@ -3,9 +3,9 @@ package gqlerrors import ( "fmt" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql-go/language/location" + "github.com/chris-ramon/graphql-go/language/source" ) type Error struct { diff --git a/gqlerrors/formatted.go b/gqlerrors/formatted.go index aaf054c8..4b630172 100644 --- a/gqlerrors/formatted.go +++ b/gqlerrors/formatted.go @@ -3,7 +3,7 @@ package gqlerrors import ( "errors" - "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql-go/language/location" ) type FormattedError struct { diff --git a/gqlerrors/located.go b/gqlerrors/located.go index 87029238..62a17c42 100644 --- a/gqlerrors/located.go +++ b/gqlerrors/located.go @@ -1,7 +1,7 @@ package gqlerrors import ( - "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql-go/language/ast" ) func NewLocatedError(err interface{}, nodes []ast.Node) *Error { diff --git a/gqlerrors/syntax.go b/gqlerrors/syntax.go index 17a283a8..ed00a954 100644 --- a/gqlerrors/syntax.go +++ b/gqlerrors/syntax.go @@ -4,9 +4,9 @@ import ( "fmt" "regexp" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql-go/language/location" + "github.com/chris-ramon/graphql-go/language/source" ) func NewSyntaxError(s *source.Source, position int, description string) *Error { diff --git a/graphql.go b/graphql.go index 7c712e8a..56dfc67c 100644 --- a/graphql.go +++ b/graphql.go @@ -1,8 +1,8 @@ package graphql import ( - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/source" ) type Params struct { diff --git a/introspection.go b/introspection.go index 27286741..d1f71808 100644 --- a/introspection.go +++ b/introspection.go @@ -4,8 +4,8 @@ import ( "fmt" "reflect" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/printer" + "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql-go/language/printer" ) const ( diff --git a/introspection_test.go b/introspection_test.go index 86f58224..ba5e354c 100644 --- a/introspection_test.go +++ b/introspection_test.go @@ -4,8 +4,8 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/location" ) func g(t *testing.T, p Params) *Result { diff --git a/language/ast/arguments.go b/language/ast/arguments.go index 93cc7b60..a63f2334 100644 --- a/language/ast/arguments.go +++ b/language/ast/arguments.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql-go/language/kinds" ) // Argument implements Node diff --git a/language/ast/definitions.go b/language/ast/definitions.go index 38155365..a0beaf3b 100644 --- a/language/ast/definitions.go +++ b/language/ast/definitions.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql-go/language/kinds" ) type Definition interface { diff --git a/language/ast/directives.go b/language/ast/directives.go index 7dd49269..25949360 100644 --- a/language/ast/directives.go +++ b/language/ast/directives.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql-go/language/kinds" ) // Directive implements Node diff --git a/language/ast/document.go b/language/ast/document.go index 34385da9..2bbfbe6f 100644 --- a/language/ast/document.go +++ b/language/ast/document.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql-go/language/kinds" ) // Document implements Node diff --git a/language/ast/location.go b/language/ast/location.go index 6f60120c..e0915aad 100644 --- a/language/ast/location.go +++ b/language/ast/location.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/language/source" ) type Location struct { diff --git a/language/ast/name.go b/language/ast/name.go index 645f1bfc..fd14c06b 100644 --- a/language/ast/name.go +++ b/language/ast/name.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql-go/language/kinds" ) // Name implements Node diff --git a/language/ast/selections.go b/language/ast/selections.go index 0fe5a4fc..ffadc41d 100644 --- a/language/ast/selections.go +++ b/language/ast/selections.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql-go/language/kinds" ) type Selection interface { diff --git a/language/ast/type_definitions.go b/language/ast/type_definitions.go index 18b07503..a2b00c82 100644 --- a/language/ast/type_definitions.go +++ b/language/ast/type_definitions.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql-go/language/kinds" ) // Ensure that all typeDefinition types implements Definition interface diff --git a/language/ast/types.go b/language/ast/types.go index 146217c3..68974b3b 100644 --- a/language/ast/types.go +++ b/language/ast/types.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql-go/language/kinds" ) type Type interface { diff --git a/language/ast/values.go b/language/ast/values.go index 2b484a66..5114072d 100644 --- a/language/ast/values.go +++ b/language/ast/values.go @@ -1,7 +1,7 @@ package ast import ( - "github.com/chris-ramon/graphql/language/kinds" + "github.com/chris-ramon/graphql-go/language/kinds" ) type Value interface { diff --git a/language/lexer/lexer.go b/language/lexer/lexer.go index 5dccefd6..083b09bc 100644 --- a/language/lexer/lexer.go +++ b/language/lexer/lexer.go @@ -3,8 +3,8 @@ package lexer import ( "fmt" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/source" ) const ( diff --git a/language/lexer/lexer_test.go b/language/lexer/lexer_test.go index ac56ee73..1365164c 100644 --- a/language/lexer/lexer_test.go +++ b/language/lexer/lexer_test.go @@ -4,7 +4,7 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/language/source" ) type Test struct { diff --git a/language/location/location.go b/language/location/location.go index 6ec9784d..d5e44f6e 100644 --- a/language/location/location.go +++ b/language/location/location.go @@ -3,7 +3,7 @@ package location import ( "regexp" - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/language/source" ) type SourceLocation struct { diff --git a/language/printer/printer.go b/language/printer/printer.go index 676bed07..f2f71720 100644 --- a/language/printer/printer.go +++ b/language/printer/printer.go @@ -4,8 +4,8 @@ import ( "fmt" "strings" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/visitor" + "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql-go/language/visitor" ) func getMapValue(m map[string]interface{}, key string) interface{} { diff --git a/language/visitor/visitor_test.go b/language/visitor/visitor_test.go index f59ca016..0a220450 100644 --- a/language/visitor/visitor_test.go +++ b/language/visitor/visitor_test.go @@ -7,9 +7,9 @@ import ( "strings" "testing" - "github.com/chris-ramon/graphql" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql-go" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/ast" "github.com/kr/pretty" ) diff --git a/lists_test.go b/lists_test.go index b14b8223..d2b9914f 100644 --- a/lists_test.go +++ b/lists_test.go @@ -4,8 +4,8 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/location" ) func checkList(t *testing.T, testType Type, testData interface{}, expected *Result) { diff --git a/located.go b/located.go index 2f741ae7..6dd51172 100644 --- a/located.go +++ b/located.go @@ -1,8 +1,8 @@ package graphql import ( - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/ast" ) func NewLocatedError(err interface{}, nodes []ast.Node) *gqlerrors.Error { diff --git a/mutations_test.go b/mutations_test.go index c905305f..0ec135b9 100644 --- a/mutations_test.go +++ b/mutations_test.go @@ -4,8 +4,8 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/location" ) // testNumberHolder maps to numberHolderType diff --git a/nonnull_test.go b/nonnull_test.go index b208ca1a..fa3bb8bd 100644 --- a/nonnull_test.go +++ b/nonnull_test.go @@ -5,8 +5,8 @@ import ( "sort" "testing" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/location" ) var syncError = "sync" diff --git a/parser.go b/parser.go index 9ae4a0b8..30d89c14 100644 --- a/parser.go +++ b/parser.go @@ -3,10 +3,10 @@ package graphql import ( "fmt" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/lexer" - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql-go/language/lexer" + "github.com/chris-ramon/graphql-go/language/source" ) type parseFn func(parser *Parser) (interface{}, error) diff --git a/parser_test.go b/parser_test.go index fdd2c3cc..2bed6061 100644 --- a/parser_test.go +++ b/parser_test.go @@ -7,10 +7,10 @@ import ( "strings" "testing" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql-go/language/location" + "github.com/chris-ramon/graphql-go/language/source" ) func TestAcceptsOptionToNotIncludeSource(t *testing.T) { diff --git a/scalars.go b/scalars.go index 98dd67d7..41f3a56f 100644 --- a/scalars.go +++ b/scalars.go @@ -4,7 +4,7 @@ import ( "fmt" "strconv" - "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql-go/language/ast" ) var ( diff --git a/schema_parser_test.go b/schema_parser_test.go index 5253ebc2..f2f0b5ce 100644 --- a/schema_parser_test.go +++ b/schema_parser_test.go @@ -4,10 +4,10 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" - "github.com/chris-ramon/graphql/language/source" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql-go/language/location" + "github.com/chris-ramon/graphql-go/language/source" ) func parse(t *testing.T, query string) *ast.Document { diff --git a/testutil.go b/testutil.go index 0661f79e..0fd5115b 100644 --- a/testutil.go +++ b/testutil.go @@ -6,7 +6,7 @@ import ( "strconv" "testing" - "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql-go/language/ast" "github.com/kr/pretty" ) diff --git a/types.go b/types.go index 13df16fb..8e397c71 100644 --- a/types.go +++ b/types.go @@ -1,7 +1,7 @@ package graphql import ( - "github.com/chris-ramon/graphql/gqlerrors" + "github.com/chris-ramon/graphql-go/gqlerrors" ) // type Schema interface{} diff --git a/validation_test.go b/validation_test.go index 430b3490..43190c17 100644 --- a/validation_test.go +++ b/validation_test.go @@ -3,7 +3,7 @@ package graphql import ( "testing" - "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql-go/language/ast" ) var someScalarType = NewScalar(ScalarConfig{ diff --git a/validator.go b/validator.go index 24879e65..e49d19a5 100644 --- a/validator.go +++ b/validator.go @@ -1,8 +1,8 @@ package graphql import ( - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/ast" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/ast" ) type ValidationResult struct { diff --git a/values.go b/values.go index 08d812b3..5d9548f4 100644 --- a/values.go +++ b/values.go @@ -6,10 +6,10 @@ import ( "math" "reflect" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/kinds" - "github.com/chris-ramon/graphql/language/printer" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql-go/language/kinds" + "github.com/chris-ramon/graphql-go/language/printer" ) // Prepares an object map of variableValues of the correct type based on the diff --git a/variables_test.go b/variables_test.go index f3b2f154..7d9593ee 100644 --- a/variables_test.go +++ b/variables_test.go @@ -5,9 +5,9 @@ import ( "reflect" "testing" - "github.com/chris-ramon/graphql/gqlerrors" - "github.com/chris-ramon/graphql/language/ast" - "github.com/chris-ramon/graphql/language/location" + "github.com/chris-ramon/graphql-go/gqlerrors" + "github.com/chris-ramon/graphql-go/language/ast" + "github.com/chris-ramon/graphql-go/language/location" ) var testComplexScalar *Scalar = NewScalar(ScalarConfig{