Skip to content

Commit

Permalink
refactor: enumerate legal field locations, rather than regexp-matching
Browse files Browse the repository at this point in the history
  • Loading branch information
speezepearson committed Mar 19, 2022
1 parent 1feb03c commit 10dda97
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
34 changes: 33 additions & 1 deletion internal/schema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,10 @@ func parseDirectiveDef(l *common.Lexer) *types.DirectiveDefinition {

for {
loc := l.ConsumeIdent()
if ok, err := regexp.MatchString("^[A-Z_]+$", loc); err != nil || !ok {
if _, ok := legalDirectiveFieldLocations[loc]; !ok {
l.SyntaxError(fmt.Sprintf("%q is not a legal directive location (options: %v)", loc, legalDirectiveFieldLocationsSlice))
}
if ok, err := regexp.MatchString("^[A-Z][A-Z_]*$", loc); err != nil || !ok {
l.SyntaxError(fmt.Sprintf("expected directive location-spec to be SNAKE_CASE, but got %q", loc))
}
d.Locations = append(d.Locations, loc)
Expand Down Expand Up @@ -596,3 +599,32 @@ func parseFieldsDef(l *common.Lexer) types.FieldsDefinition {
}
return fields
}

var legalDirectiveFieldLocations = map[string]struct{}{
"SCHEMA": {},
"SCALAR": {},
"OBJECT": {},
"FIELD_DEFINITION": {},
"ARGUMENT_DEFINITION": {},
"INTERFACE": {},
"UNION": {},
"ENUM": {},
"ENUM_VALUE": {},
"INPUT_OBJECT": {},
"INPUT_FIELD_DEFINITION": {},
"QUERY": {},
"MUTATION": {},
"SUBSCRIPTION": {},
"FIELD": {},
"FRAGMENT_DEFINITION": {},
"FRAGMENT_SPREAD": {},
"INLINE_FRAGMENT": {},
"VARIABLE_DEFINITION": {},
}
var legalDirectiveFieldLocationsSlice = func() []string {
var words []string
for loc, _ := range legalDirectiveFieldLocations {
words = append(words, loc)
}
return words
}()
7 changes: 4 additions & 3 deletions internal/schema/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package schema_test

import (
"fmt"
"strings"
"testing"

"github.com/graph-gophers/graphql-go/internal/schema"
Expand Down Expand Up @@ -912,9 +913,9 @@ Second line of the description.
scalar MyScalar @mydirective
`,
validateError: func(err error) error {
msg := `graphql: syntax error: expected directive location-spec to be SNAKE_CASE, but got "on" (line 2, column 33)`
if err == nil || err.Error() != msg {
return fmt.Errorf("expected error %q, but got %q", msg, err)
prefix := `graphql: syntax error: "on" is not a legal directive location`
if err == nil || !strings.HasPrefix(err.Error(), prefix) {
return fmt.Errorf("expected error starting with %q, but got %q", prefix, err)
}
return nil
},
Expand Down

0 comments on commit 10dda97

Please sign in to comment.