Add structs and corresponding API routes
This commit is contained in:
parent
16d2285ff3
commit
977a75819d
12 changed files with 942 additions and 1 deletions
73
api/tag.go
Normal file
73
api/tag.go
Normal file
|
@ -0,0 +1,73 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"git.nemunai.re/checkhome/struct"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
router.GET("/api/tags/", apiHandler(func (_ httprouter.Params, _ []byte) (interface{}, error) {
|
||||
return ckh.GetTags()
|
||||
}))
|
||||
router.POST("/api/tags/", apiHandler(newTag))
|
||||
router.DELETE("/api/tags/", apiHandler(func (_ httprouter.Params, _ []byte) (interface{}, error) {
|
||||
return ckh.ClearTags()
|
||||
}))
|
||||
|
||||
router.GET("/api/tags/:tid", apiHandler(tagHandler(func (tag ckh.Tag, _ []byte) (interface{}, error) {
|
||||
return tag, nil
|
||||
})))
|
||||
router.PUT("/api/tags/:tid", apiHandler(tagHandler(updateTag)))
|
||||
router.DELETE("/api/tags/:tid", apiHandler(tagHandler(func (tag ckh.Tag, _ []byte) (interface{}, error) {
|
||||
return tag.Delete()
|
||||
})))
|
||||
}
|
||||
|
||||
func tagHandler(f func(ckh.Tag, []byte) (interface{}, error)) func(httprouter.Params, []byte) (interface{}, error) {
|
||||
return func(ps httprouter.Params, body []byte) (interface{}, error) {
|
||||
if tid, err := strconv.ParseInt(string(ps.ByName("tid")), 10, 64); err != nil {
|
||||
return nil, err
|
||||
} else if tag, err := ckh.GetTag(tid); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return f(tag, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newTag(_ httprouter.Params, body []byte) (interface{}, error) {
|
||||
var ut ckh.Tag
|
||||
if err := json.Unmarshal(body, &ut); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(ut.Label) == 0 {
|
||||
return nil, errors.New("Tag's label cannot be empty")
|
||||
}
|
||||
|
||||
return ckh.NewTag(ut.Label)
|
||||
}
|
||||
|
||||
func updateTag(tag ckh.Tag, body []byte) (interface{}, error) {
|
||||
var ut ckh.Tag
|
||||
if err := json.Unmarshal(body, &ut); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(ut.Label) == 0 {
|
||||
return nil, errors.New("Tag's label cannot be empty")
|
||||
}
|
||||
|
||||
ut.Id = tag.Id
|
||||
|
||||
if _, err := ut.Update(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return ut, nil
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue