-
Notifications
You must be signed in to change notification settings - Fork 12
/
typedefs.go
73 lines (63 loc) · 1.94 KB
/
typedefs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package tools
import (
"fmt"
"strings"
"github.com/graphql-go/graphql/language/ast"
"github.com/graphql-go/graphql/language/parser"
"github.com/graphql-go/graphql/language/printer"
"github.com/graphql-go/graphql/language/source"
)
// ConcatenateTypeDefs combines one ore more typeDefs into an ast Document
func (c *ExecutableSchema) ConcatenateTypeDefs() (*ast.Document, error) {
switch c.TypeDefs.(type) {
case string:
return c.concatenateTypeDefs([]string{c.TypeDefs.(string)})
case []string:
return c.concatenateTypeDefs(c.TypeDefs.([]string))
case func() []string:
return c.concatenateTypeDefs(c.TypeDefs.(func() []string)())
}
return nil, fmt.Errorf("unsupported TypeDefs value. Must be one of string, []string, or func() []string")
}
// performs the actual concatenation of the types by parsing each
// typeDefs string and converting each definition into a string
// then creating a unique list of all definitions and finally
// printing them as a single definition and returning the parsed document
func (c *ExecutableSchema) concatenateTypeDefs(typeDefs []string) (*ast.Document, error) {
resolvedTypes := map[string]interface{}{}
for _, defs := range typeDefs {
doc, err := parser.Parse(parser.ParseParams{
Source: &source.Source{
Body: []byte(defs),
Name: "GraphQL",
},
})
if err != nil {
return nil, err
}
// if there is only 1 typedef, no de-duplication needs to happen
if len(typeDefs) == 1 {
return doc, nil
}
for _, typeDef := range doc.Definitions {
if def := printer.Print(typeDef); def != nil {
stringDef := strings.TrimSpace(def.(string))
resolvedTypes[stringDef] = nil
}
}
}
typeArray := []string{}
for def := range resolvedTypes {
typeArray = append(typeArray, def)
}
doc, err := parser.Parse(parser.ParseParams{
Source: &source.Source{
Body: []byte(strings.Join(typeArray, "\n")),
Name: "GraphQL",
},
})
if err != nil {
return nil, err
}
return doc, nil
}