107 lines
2.4 KiB
Go
107 lines
2.4 KiB
Go
package routes
|
|
|
|
import (
|
|
"encoding/json"
|
|
"gitea.deepak.science/deepak/gogmagog/models"
|
|
"github.com/go-chi/chi"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
// NewPlanRouter returns the http.Handler for the passed in model to route plan methods.
|
|
func NewPlanRouter(m *models.Model) http.Handler {
|
|
router := chi.NewRouter()
|
|
router.Get("/", getAllPlansFunc(m))
|
|
router.Post("/", postPlanFunc(m))
|
|
router.Get("/{planid}", getPlanByIDFunc(m))
|
|
return router
|
|
}
|
|
|
|
func getAllPlansFunc(m *models.Model) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
plans, err := m.Plans()
|
|
if err != nil {
|
|
serverError(w, err)
|
|
return
|
|
}
|
|
w.Header().Add("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(plans); err != nil {
|
|
serverError(w, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func getPlanByIDFunc(m *models.Model) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.Atoi(chi.URLParam(r, "planid"))
|
|
if err != nil {
|
|
notFoundHandler(w, r)
|
|
return
|
|
}
|
|
plan, err := m.Plan(id)
|
|
if err != nil {
|
|
if models.IsNotFoundError(err) {
|
|
notFoundHandler(w, r)
|
|
return
|
|
}
|
|
serverError(w, err)
|
|
return
|
|
|
|
}
|
|
w.Header().Add("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(plan); err != nil {
|
|
serverError(w, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
type createPlanResponse struct {
|
|
CreatedPlan *models.Plan `json:"created_plan"`
|
|
ID int64 `json:"id"`
|
|
}
|
|
|
|
func postPlanFunc(m *models.Model) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
r.Body = http.MaxBytesReader(w, r.Body, 1024)
|
|
dec := json.NewDecoder(r.Body)
|
|
dec.DisallowUnknownFields()
|
|
var p models.Plan
|
|
err := dec.Decode(&p)
|
|
if err != nil {
|
|
badRequestError(w, err)
|
|
return
|
|
}
|
|
err = dec.Decode(&struct{}{})
|
|
if err != io.EOF {
|
|
badRequestError(w, err)
|
|
return
|
|
}
|
|
|
|
// Map the fields we allow to be set to the plan to be created.
|
|
plan := &models.Plan{PlanDate: p.PlanDate, UserID: p.UserID}
|
|
id, err := m.AddPlan(plan)
|
|
if err != nil {
|
|
serverError(w, err)
|
|
return
|
|
}
|
|
plan, err = m.Plan(id)
|
|
if err != nil {
|
|
serverError(w, err)
|
|
return
|
|
}
|
|
|
|
response := &createPlanResponse{
|
|
CreatedPlan: plan,
|
|
ID: int64(id),
|
|
}
|
|
w.WriteHeader(http.StatusCreated)
|
|
w.Header().Add("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(response); err != nil {
|
|
serverError(w, err)
|
|
}
|
|
|
|
}
|
|
}
|