-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
104 lines (85 loc) · 2.13 KB
/
main.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
libflag "github.com/Wryte/graphql-client-generator/flag"
generate "github.com/Wryte/graphql-client-generator/generate"
graphql "github.com/Wryte/graphql-client-generator/graphql"
)
var (
endpoint string
generateInput string
headers libflag.HTTPHeaders
)
type schemaWrap struct {
Data struct {
Schema graphql.Schema `json:"__schema"`
} `json:"data"`
}
func main() {
flag.StringVar(&endpoint, "endpoint", "", "graphql endpoint for introspection query")
flag.Var(&headers, "header", "header for introspection query")
flag.StringVar(&generateInput, "generate", "all", "items to generate (all,functions,types)")
flag.Parse()
bytes, err := getSchema()
if err != nil {
panic(fmt.Errorf("getting schema: %w", err))
}
w := schemaWrap{}
err = json.Unmarshal(bytes, &w)
if err != nil {
panic(fmt.Errorf("unmarshalling json: %w", err))
}
w.Data.Schema.Init()
generator := generate.NewGenerator(os.Stdout, w.Data.Schema)
switch generateInput {
case "all":
err = generator.Write()
case "functions":
err = generator.WriteFunctions()
case "types":
err = generator.WriteTypes()
default:
fmt.Println("invalid value for generate flag")
}
if err != nil {
panic(fmt.Errorf("generating files: %w", err))
}
}
func getSchema() ([]byte, error) {
schemaQueryFile, err := os.Open("schemaQuery.graphql")
if err != nil {
return nil, fmt.Errorf("reading schema file: %w", err)
}
defer schemaQueryFile.Close()
bytes, err := ioutil.ReadAll(schemaQueryFile)
if err != nil {
return nil, fmt.Errorf("reading whole file: %w", err)
}
url, err := url.Parse(endpoint)
if err != nil {
return nil, fmt.Errorf("parsing url: %w", err)
}
req := graphql.Request{
URL: url,
Query: string(bytes),
Header: http.Header{
"Content-Type": []string{"application/json"},
},
}
for _, h := range headers {
req.Header.Add(h.Name, h.Value)
}
c := graphql.Client{}
bytes, err = c.Query(context.Background(), req)
if err != nil {
return nil, fmt.Errorf("running introspection query: %w", err)
}
return bytes, nil
}