-
Notifications
You must be signed in to change notification settings - Fork 0
/
appstore_update.go
54 lines (44 loc) · 1.31 KB
/
appstore_update.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
package appstore
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type updateResource struct {
ID string `json:"id"`
Type resourceType `json:"type"`
Attr any `json:"attributes"`
}
func doUpdate[T any](c *Client, ctx context.Context, url string, resource updateResource) (*Resource[T], error) {
body, err := json.Marshal(struct {
Data any `json:"data"`
}{resource})
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, url, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
token, err := c.tokenSource.Token()
if err != nil {
return nil, fmt.Errorf("failed to get token: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
rp := new(response[Resource[T]])
if err := json.NewDecoder(resp.Body).Decode(rp); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
return &rp.Data, nil
}