-
Notifications
You must be signed in to change notification settings - Fork 22
/
files.go
113 lines (88 loc) · 2.47 KB
/
files.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
package api
import (
"context"
"fmt"
graphql "github.com/cli/shurcooL-graphql"
"io"
"mime/multipart"
"net/http"
"net/url"
"golang.org/x/sync/errgroup"
)
type Files struct {
client *Client
}
type File struct {
ID string
Name string
ContentHash string
}
func (c *Client) Files() *Files { return &Files{client: c} }
func (f *Files) List(viewName string) ([]File, error) {
var query struct {
SearchDomain struct {
Files []File
} `graphql:"searchDomain(name:$viewName)"`
}
variables := map[string]interface{}{
"viewName": graphql.String(viewName),
}
err := f.client.Query(&query, variables)
return query.SearchDomain.Files, err
}
func (f *Files) Delete(viewName string, fileName string) error {
var query struct {
RemoveFile struct {
// We have to make a selection, so just take __typename
Typename graphql.String `graphql:"__typename"`
} `graphql:"removeFile(name:$viewName, fileName: $fileName)"`
}
variables := map[string]interface{}{
"viewName": graphql.String(viewName),
"fileName": graphql.String(fileName),
}
return f.client.Mutate(&query, variables)
}
func (f *Files) Upload(viewName string, fileName string, reader io.Reader) error {
pr, pw := io.Pipe()
multipartWriter := multipart.NewWriter(pw)
var resp *http.Response
eg, ctx := errgroup.WithContext(context.Background())
eg.Go(func() error {
var err error
resp, err = f.client.HTTPRequestContext(ctx, http.MethodPost, fmt.Sprintf("api/v1/dataspaces/%s/files", url.PathEscape(viewName)), pr, multipartWriter.FormDataContentType())
return err
})
eg.Go(func() error {
defer pw.Close()
file, err := multipartWriter.CreateFormFile("file", fileName)
if err != nil {
return err
}
_, err = io.Copy(file, reader)
if err != nil {
return err
}
return multipartWriter.Close()
})
err := eg.Wait()
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("server responded with %s: %s", resp.Status, string(body))
}
return nil
}
func (f *Files) Download(viewName string, fileName string) (io.Reader, error) {
resp, err := f.client.HTTPRequest(http.MethodGet, fmt.Sprintf("api/v1/dataspaces/%s/files/%s", url.PathEscape(viewName), url.PathEscape(fileName)), nil)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("server responded with %s: %s", resp.Status, string(body))
}
return resp.Body, nil
}