-
Notifications
You must be signed in to change notification settings - Fork 8
/
graphql.go
42 lines (36 loc) · 1.25 KB
/
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
package forest
import (
"bytes"
"encoding/json"
"io"
)
type Map map[string]interface{}
// GraphQLRequest is used to model both a query or a mutation request
type GraphQLRequest struct {
Query string `json:"query,omitempty"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}
// NewGraphQLRequest returns a new Request (for query or mutation) without any variables.
func NewGraphQLRequest(query, operation string, vars ...Map) GraphQLRequest {
initVars := map[string]interface{}{}
if len(vars) > 0 {
initVars = vars[0] // merge all?
}
return GraphQLRequest{Query: query, OperationName: operation, Variables: initVars}
}
// WithVariablesFromString returns a copy of the request with decoded variables. Returns an error if the jsonhash cannot be converted.
func (r GraphQLRequest) WithVariablesFromString(jsonhash string) (GraphQLRequest, error) {
vars := map[string]interface{}{}
err := json.Unmarshal([]byte(jsonhash), &vars)
if err != nil {
return r, err
}
r.Variables = vars
return r, nil
}
// Reader returns a new reader for sending it using a HTTP request.
func (r GraphQLRequest) Reader() io.Reader {
data, _ := json.Marshal(r)
return bytes.NewReader(data)
}