-
Notifications
You must be signed in to change notification settings - Fork 1
/
resource.go
284 lines (239 loc) · 7.83 KB
/
resource.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package jsonapi
import (
"encoding/json"
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
// Payloader is used to encapsulate the One and Many payload types
type Payloader interface {
clearIncluded()
AddPagination(paginator Paginator)
}
// NulledPayload allows for raw message to inspect nulls
type NulledPayload struct {
Data ResourceObjNulls `json:"data"`
}
// OnePayload is used to represent a generic JSON API payload where a single
// resource (ResourceObj) was included as an {} in the "data" key
type OnePayload struct {
Data *ResourceObj `json:"data"`
Included []*ResourceObj `json:"included,omitempty"`
Links *Links `json:"links,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
func (p *OnePayload) clearIncluded() {
p.Included = []*ResourceObj{}
}
func (p *OnePayload) AddPagination(paginator Paginator) {
}
// ManyPayload is used to represent a generic JSON API payload where many
// resources (Nodes) were included in an [] in the "data" key
type ManyPayload struct {
Data []*ResourceObj `json:"data"`
Included []*ResourceObj `json:"included,omitempty"`
Links *Links `json:"links,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
func (p *ManyPayload) clearIncluded() {
p.Included = []*ResourceObj{}
}
func (p *ManyPayload) AddPagination(paginator Paginator) {
p.Links = paginator.GeneratePagination()
meta := Meta{}
existingMeta := p.Meta
if existingMeta != nil {
meta = *existingMeta
}
results := &Meta{
"total": paginator.GetTotal(),
}
meta["results"] = results
p.Meta = &meta
}
// ResourceObjNulls is used to represent a generic JSON API Resource with null fields
type ResourceObjNulls struct {
Type string `json:"type"`
ID string `json:"id,omitempty"`
Attributes map[string]json.RawMessage `json:"attributes,omitempty"`
}
// ResourceObj is used to represent a generic JSON API Resource
type ResourceObj struct {
Type string `json:"type"`
ID string `json:"id,omitempty"`
Attributes map[string]interface{} `json:"attributes,omitempty"`
Relationships map[string]interface{} `json:"relationships,omitempty"`
Links *Links `json:"links,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
// RelationshipOneNode is used to represent a generic has one JSON API relation
type RelationshipOneNode struct {
Data *ResourceObj `json:"data"`
Links *Links `json:"links,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
// RelationshipManyNode is used to represent a generic has many JSON API
// relation
type RelationshipManyNode struct {
Data []*ResourceObj `json:"data"`
Links *Links `json:"links,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
// Links is used to represent a `links` object.
// http://jsonapi.org/format/#document-links
type Links map[string]interface{}
func (l *Links) validate() (err error) {
// Each member of a links object is a “link”. A link MUST be represented as
// either:
// - a string containing the link’s URL.
// - an object (“link object”) which can contain the following members:
// - href: a string containing the link’s URL.
// - meta: a meta object containing non-standard meta-information about the
// link.
for k, v := range *l {
_, isString := v.(string)
_, isLink := v.(Link)
if !(isString || isLink) {
return fmt.Errorf(
"The %s member of the links object was not a string or link object",
k,
)
}
}
return
}
// Link is used to represent a member of the `links` object.
type Link struct {
Href string `json:"href"`
Meta Meta `json:"meta,omitempty"`
}
// Linkable is used to include document links in response data
// e.g. {"self": "http://example.com/posts/1"}
type Linkable interface {
JSONAPILinks() *Links
}
// RelationshipLinkable is used to include relationship links in response data
// e.g. {"related": "http://example.com/posts/1/comments"}
type RelationshipLinkable interface {
// JSONAPIRelationshipLinks will be invoked for each relationship with the corresponding relation name (e.g. `comments`)
JSONAPIRelationshipLinks(relation string) *Links
}
// Meta is used to represent a `meta` object.
// http://jsonapi.org/format/#document-meta
type Meta map[string]interface{}
// Metable is used to include document meta in response data
// e.g. {"foo": "bar"}
type Metable interface {
JSONAPIMeta() *Meta
}
// RelationshipMetable is used to include relationship meta in response data
type RelationshipMetable interface {
// JSONRelationshipMeta will be invoked for each relationship with the corresponding relation name (e.g. `comments`)
JSONAPIRelationshipMeta(relation string) *Meta
}
// Paginator allows clients to paginate the result set
type Paginator interface {
GeneratePagination() *Links
GetTotal() int64
}
type OffsetPagination struct {
URL string
Limit int64
Total int64
}
func (p *OffsetPagination) GeneratePagination() *Links {
if p.Total < p.Limit { // no pagination needed
return nil
}
// initiate the URL - if the page offset and Limit have not been set or is devoid of all
// query parameters then initialising will make string replacement a simple operation
if !strings.Contains(p.URL, "page[limit]") {
p.appendToURL("page[limit]=" + strconv.FormatInt(p.Limit, 10))
}
if !strings.Contains(p.URL, "page[offset]") {
p.appendToURL("page[offset]=0")
}
links := Links{}
limit := int64(math.Min(float64(getPageParam("Limit", p.URL)), float64(p.Limit)))
if limit == 0 {
limit = p.Limit
}
offset := int64(math.Max(float64(getPageParam("offset", p.URL)), float64(0)))
if offset > 0 {
firstUrl := p.URL
replaceParam(&firstUrl, `page[limit]`, strconv.FormatInt(limit, 10))
replaceParam(&firstUrl, `page[offset]`, strconv.FormatInt(0, 10))
links[KeyFirstPage] = firstUrl
}
if offset > limit {
prevUrl := p.URL
replaceParam(&prevUrl, `page[limit]`, strconv.FormatInt(limit, 10))
prevOffset := offset - limit
replaceParam(&prevUrl, `page[offset]`, strconv.FormatInt(prevOffset, 10))
links[KeyPreviousPage] = prevUrl
}
if offset+limit < p.Total-limit {
nextUrl := p.URL
replaceParam(&nextUrl, `page[limit]`, strconv.FormatInt(limit, 10))
nextOffset := offset + limit
replaceParam(&nextUrl, `page[offset]`, strconv.FormatInt(nextOffset, 10))
links[KeyNextPage] = nextUrl
}
if offset+limit < p.Total {
lastUrl := p.URL
replaceParam(&lastUrl, `page[limit]`, strconv.FormatInt(limit, 10))
pages := p.Total / limit
if p.Total%limit > 0 {
pages += 1
}
lastOffset := ((pages - 1) * limit)
offsetShift := offset % limit
lastOffset += offsetShift
if lastOffset > p.Total {
lastOffset -= limit
}
replaceParam(&lastUrl, `page[offset]`, strconv.FormatInt(lastOffset, 10))
links[KeyLastPage] = lastUrl
}
return &links
}
func (p *OffsetPagination) GetTotal() int64 {
return p.Total
}
func getPageParam(name, url string) int64 {
val := 0
valRe := regexp.MustCompile(fmt.Sprintf(`page\[%s\]=(\d+)`, name))
match := valRe.FindStringSubmatch(url)
if len(match) == 2 { // when we have found the \d portion
ql := match[1]
val, _ = strconv.Atoi(ql)
}
return int64(val)
}
func replaceParam(url *string, param, value string) {
var sb strings.Builder
sb.WriteString(param)
sb.WriteString("=")
sb.WriteString(value)
newParam := sb.String()
seek := fmt.Sprintf(`%s=[^&]+`, regexSafe(param))
regex := regexp.MustCompile(seek)
match := regex.ReplaceAllString(*url, newParam)
*url = match
}
func regexSafe(in string) string {
chars := []string{"]", "^", "\\", "[", ".", "(", ")", "-"}
r := strings.Join(chars, "")
re := regexp.MustCompile("([" + r + "])+")
out := re.ReplaceAllString(in, "\\$1")
return out
}
func (p *OffsetPagination) appendToURL(param string) {
if !strings.Contains(p.URL, "?") {
p.URL += "?" + param
} else {
p.URL += "&" + param
}
}