/
source_graphql.go
153 lines (129 loc) · 3.94 KB
/
source_graphql.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package source
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strings"
kitlog "github.com/go-kit/kit/log"
"github.com/go-ozzo/ozzo-validation/is"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/hashicorp/go-cleanhttp"
"github.com/machinebox/graphql"
"github.com/pkg/errors"
"github.com/samber/lo"
"github.com/stretchr/objx"
"gopkg.in/guregu/null.v3"
)
type SourceGraphQL struct {
Endpoint Credential `json:"endpoint"` // https://api.github.com/graphql
Headers map[string]Credential `json:"headers"`
Query string `json:"query"`
Result null.String `json:"result"`
Paginate struct {
NextCursor null.String `json:"next_cursor"`
} `json:"paginate,omitempty"`
}
func (s SourceGraphQL) Validate() error {
return validation.ValidateStruct(&s,
validation.Field(&s.Endpoint,
validation.Required.Error("must provide the GraphQL endpoint"),
is.URL,
),
validation.Field(&s.Query,
validation.Required.Error("must provide the GraphQL query"),
validation.By(func(value any) error {
query := value.(string)
if s.Paginate.NextCursor.Valid {
if !strings.Contains(query, "$cursor") {
return fmt.Errorf("next cursor was provided but the query has no $cursor variable")
}
} else {
// We're not cursor paginating, which means we need to provide either a page or
// an offset variable.
if !strings.Contains(query, "$page") && !strings.Contains(query, "$offset") {
return fmt.Errorf("no pagination strategy provided by the GraphQL query")
}
}
return nil
}),
),
)
}
func (s SourceGraphQL) String() string {
return fmt.Sprintf("graphql (endpoint=%s)", s.Endpoint)
}
func (s SourceGraphQL) Load(ctx context.Context, logger kitlog.Logger) ([]*SourceEntry, error) {
client := graphql.NewClient(string(s.Endpoint),
graphql.WithHTTPClient(cleanhttp.DefaultClient()))
client.Log = func(msg string) {
logger.Log("msg", msg)
}
req := graphql.NewRequest(s.Query)
for key, value := range s.Headers {
req.Header.Set(key, string(value))
}
// Infer from the query whether we should try paginating.
shouldPaginate := s.Paginate.NextCursor.Valid ||
strings.Contains(s.Query, "$page") ||
strings.Contains(s.Query, "$offset")
trySet := func(name, value string) {
if strings.Contains(s.Query, "$"+name) {
req.Var(name, value)
}
}
var (
page = 0
offset = 0
cursor *string
)
entries := []*SourceEntry{}
for {
// Some GraphQL APIs paginate using page or offset while others use cursor.
trySet("page", fmt.Sprintf("%d", page))
trySet("offset", fmt.Sprintf("%d", offset))
if cursor != nil {
req.Var("cursor", *cursor)
}
var data json.RawMessage
logger.Log("msg", "issuing GraphQL query",
"page", page, "offset", offset, "cursor", cursor)
err := client.Run(ctx, req, &data)
if err != nil {
return nil, errors.Wrap(err, "failed to execute GraphQL query")
}
resp, err := objx.FromJSON(string(data))
if err != nil {
return nil, errors.Wrap(err, "failed to parse GraphQL response")
}
result := resp.Value().Data()
if s.Result.Valid {
result = resp.Get(s.Result.String).Data()
}
if reflect.TypeOf(result).Kind() != reflect.Slice {
return nil, errors.Wrap(err, "result is not a slice of values")
}
content, err := json.Marshal(result)
if err != nil {
return nil, errors.Wrap(err, "marshalling result into JSON")
}
entries = append(entries, &SourceEntry{
Origin: s.String(),
Content: content,
})
resultCount := reflect.ValueOf(result).Len()
if resultCount == 0 || !shouldPaginate {
return entries, nil
}
page += 1
offset += resultCount
// If we've configured cursor pagination then fetch the next cursor value.
if s.Paginate.NextCursor.Valid {
value := resp.Get(s.Paginate.NextCursor.String).Str()
if value == "" {
return nil, fmt.Errorf("response did not find next cursor at '%s'", s.Paginate.NextCursor.String)
}
cursor = lo.ToPtr(value)
}
}
}