-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
72 lines (59 loc) · 1.28 KB
/
main.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
package main
import (
"errors"
"net/http"
"time"
"github.com/calvinmclean/babyapi"
)
type TODO struct {
babyapi.DefaultResource
Title string
Description string
Completed *bool
CreatedAt time.Time
}
func (t *TODO) Patch(newTODO *TODO) *babyapi.ErrResponse {
if newTODO.Title != "" {
t.Title = newTODO.Title
}
if newTODO.Description != "" {
t.Description = newTODO.Description
}
if newTODO.Completed != nil {
t.Completed = newTODO.Completed
}
return nil
}
func (t *TODO) Bind(r *http.Request) error {
err := t.DefaultResource.Bind(r)
if err != nil {
return err
}
switch r.Method {
case http.MethodPost:
t.CreatedAt = time.Now()
fallthrough
case http.MethodPut:
if t.Title == "" {
return errors.New("missing required title field")
}
}
return nil
}
func main() {
api := babyapi.NewAPI("TODOs", "/todos", func() *TODO { return &TODO{} })
api.SetGetAllFilter(func(r *http.Request) babyapi.FilterFunc[*TODO] {
return func(t *TODO) bool {
getCompletedParam := r.URL.Query().Get("completed")
// No filtering if param is not provided
if getCompletedParam == "" {
return true
}
if getCompletedParam == "true" {
return t.Completed != nil && *t.Completed
}
return t.Completed == nil || !*t.Completed
}
})
api.RunCLI()
}