/
queries.go
90 lines (76 loc) · 1.94 KB
/
queries.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
package aggregator
import (
"context"
"fmt"
"strings"
"os"
"github.com/iancoleman/strcase"
"github.com/jinzhu/inflection"
"github.com/machinebox/graphql"
)
// FetchResponse ...
type FetchResponse struct {
Result interface{} `json:"result"`
}
func sendRequest(ctx context.Context, req *graphql.Request, res interface{}) error {
URL := os.Getenv("AGGREGATOR_URL")
if URL == "" {
return fmt.Errorf("Missing required environment variable AGGREGATOR_URL")
}
client := graphql.NewClient(URL)
client.Log = func(s string) {
fmt.Println(s)
}
return client.Run(ctx, req, &res)
}
// GetEntityOptions ...
type GetEntityOptions struct {
Entity string
EntityID string
Fields []string
}
// GetEntity ...
func GetEntity(ctx context.Context, options GetEntityOptions, res interface{}) error {
query := fmt.Sprintf(`
query ($id: ID!) {
result: %s(id:$id) {
id %s
}
}
`, strcase.ToLowerCamel(options.Entity), strings.Join(options.Fields, " "))
req := graphql.NewRequest(query)
req.Var("id", options.EntityID)
return sendRequest(ctx, req, res)
}
// GetEntitiesOptions ...
type GetEntitiesOptions struct {
Entity string
Fields []string
Filter map[string]interface{}
Sort []string
Limit *int
Offset *int
}
// GetEntities ...
func GetEntities(ctx context.Context, options GetEntitiesOptions, res interface{}) error {
query := fmt.Sprintf(`
query ($filter: %sFilterType, $sort: [%sSortType], $limit: Int, $offset: Int) {
result: %s(filter:$filter,sort:$sort,limit:$limit,offset:$offset) {
items {
id %s
}
count
}
}
`, options.Entity, options.Entity, inflection.Plural(strcase.ToLowerCamel(options.Entity)), strings.Join(options.Fields, " "))
req := graphql.NewRequest(query)
req.Var("filter", options.Filter)
req.Var("sort", options.Sort)
if options.Offset != nil {
req.Var("offset", options.Offset)
}
if options.Limit != nil {
req.Var("limit", options.Limit)
}
return sendRequest(ctx, req, res)
}