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/room.go
Normal file
73
api/room.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/rooms/", apiHandler(func (_ httprouter.Params, _ []byte) (interface{}, error) {
|
||||
return ckh.GetRooms()
|
||||
}))
|
||||
router.POST("/api/rooms/", apiHandler(newRoom))
|
||||
router.DELETE("/api/rooms/", apiHandler(func (_ httprouter.Params, _ []byte) (interface{}, error) {
|
||||
return ckh.ClearRooms()
|
||||
}))
|
||||
|
||||
router.GET("/api/rooms/:rid", apiHandler(roomHandler(func (room ckh.Room, _ []byte) (interface{}, error) {
|
||||
return room, nil
|
||||
})))
|
||||
router.PUT("/api/rooms/:rid", apiHandler(roomHandler(updateRoom)))
|
||||
router.DELETE("/api/rooms/:rid", apiHandler(roomHandler(func (room ckh.Room, _ []byte) (interface{}, error) {
|
||||
return room.Delete()
|
||||
})))
|
||||
}
|
||||
|
||||
func roomHandler(f func(ckh.Room, []byte) (interface{}, error)) func(httprouter.Params, []byte) (interface{}, error) {
|
||||
return func(ps httprouter.Params, body []byte) (interface{}, error) {
|
||||
if rid, err := strconv.ParseInt(string(ps.ByName("rid")), 10, 64); err != nil {
|
||||
return nil, err
|
||||
} else if room, err := ckh.GetRoom(rid); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return f(room, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newRoom(_ httprouter.Params, body []byte) (interface{}, error) {
|
||||
var ur ckh.Room
|
||||
if err := json.Unmarshal(body, &ur); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(ur.Label) == 0 {
|
||||
return nil, errors.New("Room's label cannot be empty")
|
||||
}
|
||||
|
||||
return ckh.NewRoom(ur.Label)
|
||||
}
|
||||
|
||||
func updateRoom(room ckh.Room, body []byte) (interface{}, error) {
|
||||
var ur ckh.Room
|
||||
if err := json.Unmarshal(body, &ur); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(ur.Label) == 0 {
|
||||
return nil, errors.New("Room's label cannot be empty")
|
||||
}
|
||||
|
||||
ur.Id = room.Id
|
||||
|
||||
if _, err := ur.Update(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return ur, nil
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue