Add structs and corresponding API routes
This commit is contained in:
parent
16d2285ff3
commit
977a75819d
12 changed files with 942 additions and 1 deletions
76
api/check.go
Normal file
76
api/check.go
Normal file
|
@ -0,0 +1,76 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"git.nemunai.re/checkhome/struct"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
router.GET("/api/checks/", apiHandler(func (_ httprouter.Params, _ []byte) (interface{}, error) {
|
||||
return ckh.GetChecks()
|
||||
}))
|
||||
|
||||
router.GET("/api/rooms/:rid/items/:iid/checks/", apiHandler(itemHandler(func (item ckh.Item, _ ckh.Room, _ []byte) (interface{}, error) {
|
||||
return item.GetChecks()
|
||||
})))
|
||||
router.POST("/api/rooms/:rid/items/:iid/checks/", apiHandler(itemHandler(newCheck)))
|
||||
|
||||
router.GET("/api/rooms/:rid/items/:iid/checks/:cid", apiHandler(checkHandler(func (check ckh.Check, _ ckh.Item, _ ckh.Room, _ []byte) (interface{}, error) {
|
||||
return check, nil
|
||||
})))
|
||||
router.PUT("/api/rooms/:rid/items/:iid/checks/:cid", apiHandler(checkHandler(updateCheck)))
|
||||
router.DELETE("/api/rooms/:rid/items/:iid/checks/:cid", apiHandler(checkHandler(func (check ckh.Check, _ ckh.Item, _ ckh.Room, _ []byte) (interface{}, error) {
|
||||
return check.Delete()
|
||||
})))
|
||||
}
|
||||
|
||||
func checkHandler(f func(ckh.Check, ckh.Item, ckh.Room, []byte) (interface{}, error)) func(httprouter.Params, []byte) (interface{}, error) {
|
||||
return func(ps httprouter.Params, body []byte) (interface{}, error) {
|
||||
return itemHandler(func (item ckh.Item, room ckh.Room, _ []byte) (interface{}, error) {
|
||||
if cid, err := strconv.ParseInt(string(ps.ByName("cid")), 10, 64); err != nil {
|
||||
return nil, err
|
||||
} else if check, err := item.GetCheck(cid); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return f(check, item, room, body)
|
||||
}
|
||||
})(ps, body)
|
||||
}
|
||||
}
|
||||
|
||||
func newCheck(item ckh.Item, _ ckh.Room, body []byte) (interface{}, error) {
|
||||
var uc ckh.Check
|
||||
if err := json.Unmarshal(body, &uc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(uc.Passed) == 0 {
|
||||
return nil, errors.New("Check's state cannot be empty")
|
||||
}
|
||||
|
||||
return item.NewCheck(ckh.User{}, uc.Passed, uc.Comment)
|
||||
}
|
||||
|
||||
func updateCheck(check ckh.Check, _ ckh.Item, _ ckh.Room, body []byte) (interface{}, error) {
|
||||
var uc ckh.Check
|
||||
if err := json.Unmarshal(body, &uc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(uc.Passed) == 0 {
|
||||
return nil, errors.New("Check's state cannot be empty")
|
||||
}
|
||||
|
||||
uc.Id = check.Id
|
||||
|
||||
if _, err := uc.Update(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return uc, nil
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue