-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgontentful.go
198 lines (167 loc) · 5.38 KB
/
gontentful.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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package gontentful
import (
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
)
const (
timeout = 30 * time.Second
pathSpaces = "/spaces/%s"
pathEnvironments = "/environments/%s"
pathSpacesCreate = "/spaces"
pathEntries = pathSpaces + pathEnvironments + "/entries"
pathEntry = pathEntries + "/%s"
pathEntriesPublish = pathEntry + "/published"
pathEntriesArchive = pathEntry + "/archived"
pathSync = pathSpaces + pathEnvironments + "/sync"
pathAssets = pathSpaces + pathEnvironments + "/assets"
pathAssetsProcess = pathAssets + "/%s/files/%s/process"
pathAssetsPublished = pathAssets + "/%s/published"
pathUploads = pathSpaces + "/uploads"
pathContentTypes = pathSpaces + pathEnvironments + "/content_types"
pathContentType = pathContentTypes + "/%s"
pathContentTypesPublish = pathContentType + "/published"
pathLocales = pathSpaces + "/locales"
headerContentfulContentType = "X-Contentful-Content-Type"
headerContentfulVersion = "X-Contentful-Version"
headerContentfulOrganization = "X-Contentful-Organization"
headerContentType = "Content-Type"
headerAuthorization = "Authorization"
)
type Client struct {
client *http.Client
headers map[string]string
Options *ClientOptions
AfterRequest func(c *Client, req *http.Request, res *http.Response, elapsed time.Duration)
common service
Entries *EntriesService
Spaces *SpacesService
Locales *LocalesService
Assets *AssetsService
Uploads *UploadsService
ContentTypes *ContentTypesService
}
type service struct {
client *Client
}
type ClientOptions struct {
OrgID string
SpaceID string
EnvironmentID string
CdnToken string
PreviewToken string
CmaToken string
CdnURL string
PreviewURL string
CmaURL string
UsePreview bool
}
func NewClient(options *ClientOptions) *Client {
httpClient := &http.Client{
Timeout: timeout,
}
client := &Client{
Options: options,
client: httpClient,
headers: getHeadersMap(options.OrgID),
}
client.common.client = client
client.Entries = (*EntriesService)(&client.common)
client.Spaces = (*SpacesService)(&client.common)
client.Locales = (*LocalesService)(&client.common)
client.Assets = (*AssetsService)(&client.common)
client.Uploads = (*UploadsService)(&client.common)
client.ContentTypes = (*ContentTypesService)(&client.common)
return client
}
func getHeadersMap(orgID string) map[string]string {
return map[string]string{
headerContentfulOrganization: orgID,
headerContentType: "application/vnd.contentful.delivery.v1+json",
}
}
func (c *Client) get(path string, query url.Values) ([]byte, error) {
host := ""
authToken := ""
if c.Options.UsePreview {
host = c.Options.PreviewURL
authToken = c.Options.PreviewToken
} else {
host = c.Options.CdnURL
authToken = c.Options.CdnToken
}
return c.req(http.MethodGet, path, query, nil, host, authToken)
}
func (c *Client) getCMA(path string, query url.Values) ([]byte, error) {
return c.req(http.MethodGet, path, query, nil, c.Options.CmaURL, c.Options.CmaToken)
}
func (c *Client) post(path string, body io.Reader) ([]byte, error) {
return c.req(http.MethodPost, path, nil, body, c.Options.CmaURL, c.Options.CmaToken)
}
func (c *Client) put(path string, body io.Reader) ([]byte, error) {
return c.req(http.MethodPut, path, nil, body, c.Options.CmaURL, c.Options.CmaToken)
}
func (c *Client) delete(path string) ([]byte, error) {
return c.req(http.MethodDelete, path, nil, nil, c.Options.CmaURL, c.Options.CmaToken)
}
func (c *Client) req(method string, path string, query url.Values, body io.Reader, host string, authToken string) ([]byte, error) {
u := &url.URL{
Scheme: "https",
Host: host,
Path: path,
}
u.RawQuery = query.Encode()
// fmt.Println(fmt.Sprintf("%s%s?%s", host, path, u.RawQuery))
req, err := http.NewRequest(method, u.String(), body)
if err != nil {
return nil, err
}
// set headers
for key, value := range c.headers {
if value != "" {
req.Header.Set(key, value)
}
}
// fmt.Println(fmt.Sprintf("%s: Bearer %s", headerAuthorization, authToken))
// add auth header
req.Header.Set(headerAuthorization, fmt.Sprintf("Bearer %s", authToken))
return c.do(req)
}
func (c *Client) do(req *http.Request) ([]byte, error) {
start := time.Now()
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if c.AfterRequest != nil {
c.AfterRequest(c, req, res, time.Since(start))
}
if res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusBadRequest {
// clear headers so that they will not infect the next request.
c.headers = getHeadersMap(c.Options.OrgID)
// return the response
return io.ReadAll(res.Body)
}
apiError := parseError(req, res)
// return apiError if it is not rate limit error
if _, ok := apiError.(RateLimitExceededError); !ok {
return nil, apiError
}
resetHeader := res.Header.Get("x-contentful-ratelimit-reset")
// return apiError if Ratelimit-Reset header is not presented
if resetHeader == "" {
return nil, apiError
}
// wait X-Contentful-Ratelimit-Reset amount of seconds
waitSeconds, err := strconv.Atoi(resetHeader)
if err != nil {
return nil, apiError
}
// retry on rate limit
time.Sleep(time.Second * time.Duration(waitSeconds))
return c.do(req)
}