-
Notifications
You must be signed in to change notification settings - Fork 0
/
articles_resource.go
88 lines (75 loc) · 2.17 KB
/
articles_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
package resources
import (
"context"
"net/http"
"github.com/fivestar/resozyme"
"github.com/fivestar/resozyme/_examples/model"
"github.com/fivestar/resozyme/_examples/repos"
)
// NewArticlesResource creates an ArticlesResource.
func NewArticlesResource(ctx context.Context) resozyme.Resource {
return &ArticlesResource{
Base: resozyme.NewBase(ctx),
view: &articlesView{},
articleRepo: repos.NewArticleRepository(),
}
}
// ArticlesResource is a resource.
type ArticlesResource struct {
*resozyme.Base
view *articlesView
postView *articleView
articleRepo repos.ArticleRepository
}
// articlesView is a view for the ArticlesResource.
type articlesView struct{}
// View returns a resource view.
func (resc *ArticlesResource) View() interface{} {
if resc.postView != nil {
return resc.postView
}
return resc.view
}
// Href returns a path of resource.
func (resc *ArticlesResource) Href() string {
return "/articles"
}
// Bind binds specified values to the resource.
func (resc *ArticlesResource) Bind(i interface{}) {
switch v := i.(type) {
case []*model.Article:
var rescs []resozyme.Resource
for _, article := range v {
rescs = append(rescs, resozyme.BindTo(NewArticleResource(resc.Context()), article))
}
resc.EmbedCollection("articles", rescs)
}
}
// OnGet handles the GET request.
func (resc *ArticlesResource) OnGet(w http.ResponseWriter, r *http.Request) {
articles, err := resc.articleRepo.FindLatest(5)
if err != nil {
resc.SetCode(http.StatusInternalServerError)
resc.SetError(err)
return
}
resozyme.BindTo(resc, articles)
}
// OnPost handles the POST request.
func (resc *ArticlesResource) OnPost(w http.ResponseWriter, r *http.Request) {
article := &model.Article{}
if err := submitArticle(r, &articleView{}, article); err != nil {
resc.SetCode(http.StatusBadRequest)
resc.SetError(err)
return
}
if err := resc.articleRepo.Add(article); err != nil {
resc.SetCode(http.StatusInternalServerError)
resc.SetError(err)
return
}
aResc := resozyme.BindTo(NewArticleResource(resc.Context()), article)
resc.postView = aResc.View().(*articleView)
resc.SetCode(http.StatusCreated)
resc.Header().Add("Location", aResc.Href())
}