-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.go
99 lines (82 loc) · 2.27 KB
/
plugin.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
package feeds
import (
"fmt"
"github.com/alexedwards/flow"
"github.com/rumorsflow/rumors/internal/api/middleware/authz"
"github.com/rumorsflow/rumors/internal/api/util"
"github.com/rumorsflow/rumors/internal/storage"
"github.com/rumorsflow/rumors/internal/tgbotsender"
"net/http"
)
const (
PluginName = "/api/v1/feeds"
id = "/:id"
)
type Plugin struct {
storage storage.FeedStorage
sender tgbotsender.TelegramSender
}
func (p *Plugin) Init(s storage.FeedStorage, sender tgbotsender.TelegramSender) error {
p.storage = s
p.sender = sender
return nil
}
// Name returns user-friendly plugin name
func (p *Plugin) Name() string {
return PluginName
}
func (p *Plugin) Register(mux *flow.Mux) {
mux.HandleFunc(PluginName, p.list, http.MethodGet)
mux.HandleFunc(PluginName+id, p.read, http.MethodGet)
mux.HandleFunc(PluginName, authz.IsAdmin(p.create), http.MethodPost)
mux.HandleFunc(PluginName+id, authz.IsAdmin(p.update), http.MethodPatch)
mux.HandleFunc(PluginName+id, authz.IsAdmin(p.delete), http.MethodDelete)
}
func (p *Plugin) list(w http.ResponseWriter, r *http.Request) {
criteria := util.GetCriteria(r)
data, err := p.storage.Find(r.Context(), criteria)
if err != nil {
panic(err)
}
total, err := p.storage.Count(r.Context(), criteria.Filter)
if err != nil {
panic(err)
}
util.OK(w, util.ListResponse{
Data: data,
Total: total,
Index: criteria.Index,
Size: criteria.Size,
})
}
func (p *Plugin) read(w http.ResponseWriter, r *http.Request) {
data, err := p.storage.FindById(r.Context(), util.GetId(r))
if err != nil {
panic(err)
}
util.OK(w, data)
}
func (p *Plugin) create(w http.ResponseWriter, r *http.Request) {
var dto CreateRequest
util.Bind(r, &dto)
model := dto.Feed(p.sender.Owner())
if err := p.storage.Save(r.Context(), &model); err != nil {
panic(err)
}
util.Created(w, fmt.Sprintf("%s/%s", PluginName, model.Id))
}
func (p *Plugin) update(w http.ResponseWriter, r *http.Request) {
var dto UpdateRequest
util.Bind(r, &dto)
model := dto.Feed(util.GetId(r))
if err := p.storage.Save(r.Context(), &model); err != nil {
panic(err)
}
util.NoContent(w)
}
func (p *Plugin) delete(w http.ResponseWriter, r *http.Request) {
if err := p.storage.Delete(r.Context(), util.GetId(r)); err != nil {
panic(err)
}
util.NoContent(w)
}