-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_common.go
83 lines (80 loc) · 1.91 KB
/
api_common.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
package shopify
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
)
// UploadJSONL wraps UploadJSONLWithContext using context.Background.
func (client *Client) UploadJSONL(jsonl string) (string, error) {
return client.UploadJSONLWithContext(context.Background(), jsonl)
}
// Upload JSONL string and return the stagedUploadPath used in
// bulkOperationRunMutation.
func (client *Client) UploadJSONLWithContext(ctx context.Context, jsonl string) (key string, err error) {
var uploadUrl string
var params []struct {
Name string `json:"name"`
Value string `json:"value"`
}
err = client.New(
`mutation {
stagedUploadsCreate(input: {
resource: BULK_MUTATION_VARIABLES,
filename: "bulk_op_vars",
mimeType: "text/jsonl",
httpMethod: POST
}) {
userErrors { field message }
stagedTargets { url parameters { name value } }
} }`,
).WithContext(ctx).Do(
&uploadUrl, "stagedUploadsCreate.stagedTargets.*.url",
¶ms, "stagedUploadsCreate.stagedTargets.*.parameters.*",
)
if err != nil {
return
}
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
var keyInParams string
for _, param := range params {
if param.Name == "key" {
keyInParams = param.Value
}
if err = writer.WriteField(param.Name, param.Value); err != nil {
return
}
}
var part io.Writer
part, err = writer.CreateFormFile("file", "data.jsonl")
if err != nil {
return
}
if _, err = part.Write([]byte(jsonl)); err != nil {
return
}
if err = writer.Close(); err != nil {
return
}
var req *http.Request
req, err = http.NewRequestWithContext(ctx, "POST", uploadUrl, body)
if err != nil {
return
}
req.Header.Set("Content-Type", writer.FormDataContentType())
var res *http.Response
res, err = http.DefaultClient.Do(req)
if err != nil {
return
}
res.Body.Close()
if res.StatusCode != 201 {
err = fmt.Errorf("response status is not ok: %d", res.StatusCode)
return
}
key = keyInParams
return
}