/
collection.go
88 lines (69 loc) · 1.66 KB
/
collection.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
package models
import (
"fmt"
"net/url"
"reflect"
"strconv"
"aahframework.org/aah.v0"
"github.com/train-cat/api-train/app/rest"
)
type (
// Collection of one entity
Collection struct {
Page int `json:"page"`
Limit int `json:"limit"`
Pages int `json:"pages"`
Total int `json:"total"`
rest.Hateoas
}
)
// GenerateHateoas content
func (c *Collection) GenerateHateoas(ctx *aah.Context) error {
u := ctx.Req.Unwrap().URL
links, err := generateLinks(u, c.Pages)
if err != nil {
return err
}
c.Links = *links
return c.hateoasItems(ctx)
}
func (c *Collection) hateoasItems(ctx *aah.Context) error {
v := reflect.ValueOf(c.Embedded["items"]).Elem()
var err error
switch v.Kind() {
case reflect.Slice:
for i := 0; i < v.Len(); i++ {
h, ok := v.Index(i).Interface().(rest.Hateoasable)
if ok {
if err = h.GenerateHateoas(ctx); err != nil {
return err
}
}
}
}
return nil
}
func generateLinks(u *url.URL, lastPage int) (*rest.Links, error) {
links := rest.Links{}
q := u.Query()
currentPage := 1
if q.Get(rest.QueryPage) != "" {
var err error
currentPage, err = strconv.Atoi(q.Get(rest.QueryPage))
if err != nil {
return nil, err
}
}
links[rest.LinkSelf] = rest.Link{Href: u.RequestURI()}
for link, page := range map[string]int{rest.LinkFirst: 1, rest.LinkLast: lastPage, rest.LinkPrevious: currentPage - 1, rest.LinkNext: currentPage + 1} {
if page > 0 && page <= lastPage {
q.Set(rest.QueryPage, fmt.Sprintf("%d", page))
query, err := url.QueryUnescape(q.Encode())
if err != nil {
return nil, err
}
links[link] = rest.Link{Href: fmt.Sprintf("%s?%s", u.Path, query)}
}
}
return &links, nil
}