-
Notifications
You must be signed in to change notification settings - Fork 22
/
format.go
executable file
·66 lines (54 loc) · 1.4 KB
/
format.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
package graphql
import (
"fmt"
"strings"
"github.com/vektah/gqlparser/v2/ast"
)
func formatIndentPrefix(level int) string {
acc := "\n"
// build up the prefix
for i := 0; i <= level; i++ {
acc += " "
}
return acc
}
func formatSelectionSelectionSet(level int, selectionSet ast.SelectionSet) string {
acc := " {"
// and any sub selection
acc += formatSelection(level+1, selectionSet)
acc += formatIndentPrefix(level) + "}"
return acc
}
func formatSelection(level int, selectionSet ast.SelectionSet) string {
acc := ""
for _, selection := range selectionSet {
acc += formatIndentPrefix(level)
switch selection := selection.(type) {
case *ast.Field:
// add the field name
acc += selection.Name
if len(selection.SelectionSet) > 0 {
acc += formatSelectionSelectionSet(level, selection.SelectionSet)
}
case *ast.InlineFragment:
// print the fragment name
acc += fmt.Sprintf("... on %v", selection.TypeCondition) +
formatSelectionSelectionSet(level, selection.SelectionSet)
case *ast.FragmentSpread:
// print the fragment name
acc += "..." + selection.Name
}
}
return acc
}
// FormatSelectionSet returns a pretty printed version of a selection set
func FormatSelectionSet(selection ast.SelectionSet) string {
acc := "{"
insides := formatSelection(0, selection)
if strings.TrimSpace(insides) != "" {
acc += insides + "\n}"
} else {
acc += "}"
}
return acc
}