-
Notifications
You must be signed in to change notification settings - Fork 0
/
appstore_create.go
79 lines (64 loc) · 2.11 KB
/
appstore_create.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
package appstore
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type resourceType string
const (
resourceTypeAppScreenshots = "appScreenshots"
resourceTypeAchievements = "gameCenterAchievements"
resourceTypeAchievementLocalizations = "gameCenterAchievementLocalizations"
resourceTypeAchievementImages = "gameCenterAchievementImages"
)
type createResource struct {
Type resourceType `json:"type"`
Attr any `json:"attributes"`
Relations relations `json:"relationships"`
}
type relations struct {
GameCenter *relationd `json:"gameCenterDetail,omitempty"`
Achievement *relationd `json:"gameCenterAchievement,omitempty"`
AchievementLocalization *relationd `json:"gameCenterAchievementLocalization,omitempty"`
AppScreenshotSet *relationd `json:"appScreenshotSet,omitempty"`
}
type relationd struct {
Data relation `json:"data"`
}
type relation struct {
ID string `json:"id"`
Type string `json:"type"`
}
func doCreate[T any](c *Client, ctx context.Context, url string, resource createResource) (*Resource[T], error) {
body, err := json.Marshal(struct {
Data createResource `json:"data"`
}{resource})
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, 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.StatusCreated {
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
}