-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgqlyzer.go
74 lines (62 loc) · 1.4 KB
/
gqlyzer.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
74
package gqlyzer
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/kumparan/gqlyzer/token/operation"
"github.com/kumparan/gqlyzer/token"
)
// Lexer definition
type Lexer struct {
input string
parseStack []rune
cursor int
}
// New use to init lexer
func New(gql string) (l *Lexer) {
l = &Lexer{
input: gql,
}
l.Reset()
return l
}
// Reset reset the state of lexer
func (l *Lexer) Reset() {
l.parseStack = []rune{}
l.cursor = 0
}
// Parse operation without variable
func (l *Lexer) Parse() (token.Operation, error) {
return l.parseOperation()
}
// ParseOperationType parse operation type only
func (l *Lexer) ParseOperationType() (operation.Type, error) {
ot, _, err := l.parseOperationType()
return ot, err
}
// ParseWithVariables parse operation with variable
func (l *Lexer) ParseWithVariables(variables string) (token.Operation, error) {
variableMap := make(map[string]interface{})
err := json.Unmarshal([]byte(variables), &variableMap)
if err != nil {
return token.Operation{}, err
}
for key, content := range variableMap {
var s string
switch c := content.(type) {
case string:
s = fmt.Sprintf("\"%s\"", c)
case int:
s = strconv.Itoa(c)
default:
jsonStr, err := json.Marshal(content)
if err != nil {
return token.Operation{}, err
}
s = string(jsonStr)
}
l.input = strings.ReplaceAll(l.input, "$"+key, s)
}
return l.parseOperation()
}