74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
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
|
|
}
|
|
}
|