~bigbes/core-go

ref: bdb0f7e8ad77b331f7a0d3ec5a60733250095233 core-go/client/graphql.go -rw-r--r-- 4.7 KiB
bdb0f7e8 — Drew DeVault server: disable logging for release mode 1 year, 1 month ago
                                                                                
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package client

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"net/textproto"

	"git.sr.ht/~sircmpwn/core-go/config"
	"git.sr.ht/~sircmpwn/core-go/crypto"

	"github.com/99designs/gqlgen/graphql"
	"github.com/vektah/gqlparser/v2/gqlerror"
)

type GraphQLQuery struct {
	Query     string                    `json:"query"`
	Variables map[string]interface{}    `json:"variables"`
	Uploads   map[string]graphql.Upload `json:"-"`
}

type InternalAuth struct {
	Name     string `json:"name",omitempty`
	ClientID string `json:"client_id"`
	NodeID   string `json:"node_id"`
}

func Do(ctx context.Context, username string, svc string,
	query GraphQLQuery, result interface{},
) error {
	conf := config.ForContext(ctx)
	origin, _ := conf.Get(svc, "api-origin")
	if origin == "" {
		origin = config.GetOrigin(conf, svc, false)
	}
	if origin == "" {
		panic(fmt.Errorf("No %s origin specified in config.ini", svc))
	}

	var (
		contentType string
		reader      io.Reader
	)

	if len(query.Uploads) > 0 {
		var (
			body    *multipart.Writer
			buf     bytes.Buffer
			filemap map[string][]string
			uploads []graphql.Upload
			h       textproto.MIMEHeader
		)

		// Prepare the "map" field which associates the index of each
		// uploaded file to a variable name. Related 'null' values are
		// required in the variables map.
		filemap = make(map[string][]string)
		uploads = make([]graphql.Upload, 0, len(query.Uploads))
		i := 0
		for name, upload := range query.Uploads {
			filemap[fmt.Sprintf("%d", i)] = []string{
				fmt.Sprintf("variables.%s", name),
			}
			query.Variables[name] = nil
			uploads = append(uploads, upload)
			i++
		}

		// Create a new multipart body
		body = multipart.NewWriter(&buf)

		// Add the GraphQLQuery object serialized as JSON as a first
		// multipart field named "operations".
		h = make(textproto.MIMEHeader)
		h.Add("Content-Disposition", `form-data; name="operations"`)
		h.Add("Content-Type", "application/json")
		pw, _ := body.CreatePart(h)
		if err := json.NewEncoder(pw).Encode(query); err != nil {
			panic(err) // Programmer error
		}

		// The second multipart field is the filemap we created
		// previously. The field name must be "map" and be serialized
		// as JSON.
		h = make(textproto.MIMEHeader)
		h.Add("Content-Disposition", `form-data; name="map"`)
		h.Add("Content-Type", "application/json")
		pw, _ = body.CreatePart(h)
		if err := json.NewEncoder(pw).Encode(filemap); err != nil {
			panic(err) // Programmer error
		}

		// Finally, add one multipart field per upload. Use the upload
		// index as field name. The filename value is optional and can
		// remain empty. If the content-type is not set, assume
		// application/octet-stream as default.
		for i, upload := range uploads {
			h = make(textproto.MIMEHeader)
			h.Add("Content-Disposition", fmt.Sprintf(
				`form-data; name="%d"; filename=%q`, i, upload.Filename))
			if upload.ContentType == "" {
				upload.ContentType = "application/octet-stream"
			}
			h.Add("Content-Type", upload.ContentType)
			pw, _ = body.CreatePart(h)
			if _, err := io.Copy(pw, upload.File); err != nil {
				return err
			}
		}
		if err := body.Close(); err != nil {
			return err
		}
		reader = &buf
		contentType = fmt.Sprintf(
			"multipart/form-data; boundary=%s", body.Boundary())
	} else {
		body, err := json.Marshal(query)
		if err != nil {
			panic(err) // Programmer error
		}
		reader = bytes.NewBuffer(body)
		contentType = "application/json"
	}

	req, err := http.NewRequestWithContext(ctx,
		"POST", fmt.Sprintf("%s/query", origin), reader)
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", contentType)
	req.Header.Add("User-Agent", "SourceHut core-go (https://git.sr.ht/~sircmpwn/core-go)")
	auth := InternalAuth{
		Name:     username,
		ClientID: config.ServiceName(ctx),
		// TODO: Populate this:
		NodeID: "core-go",
	}
	authBlob, err := json.Marshal(&auth)
	if err != nil {
		panic(err) // Programmer error
	}
	req.Header.Add("Authorization", fmt.Sprintf("Internal %s",
		crypto.Encrypt(authBlob)))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	if resp.StatusCode != 200 {
		return fmt.Errorf("%s returned status %d: %s",
			svc, resp.StatusCode, string(respBody))
	}

	var respData struct {
		Data   interface{}   `json:"data"`
		Errors gqlerror.List `json:"errors"`
	}
	respData.Data = result
	if err := json.Unmarshal(respBody, &respData); err != nil {
		return fmt.Errorf("failed to parse GraphQL response: %v", err)
	}

	if len(respData.Errors) == 1 {
		return respData.Errors[0]
	} else if len(respData.Errors) > 1 {
		return respData.Errors
	}

	return nil
}