You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.7 KiB

package api
import (
"context"
"net/http"
"strconv"
"git.brettb.xyz/goinv/server/internal/types"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
)
func (s *APIServer) setupBuildingRoutes() func(chi.Router) {
return func(r chi.Router) {
r.Get("/", makeHandler(s.getBuildings))
r.Route("/{buildingId}", func(r chi.Router) {
r.Use(s.BuildingCtx)
})
}
}
func (s *APIServer) BuildingCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
buildingIdStr := chi.URLParam(r, "buildingId")
buildingId, err := strconv.ParseUint(buildingIdStr, 10, 64)
if err != nil {
render.Render(w, r, errNotFound)
return
}
building, err := s.db.GetBuildingByID(buildingId)
if err != nil {
render.Render(w, r, errNotFound)
return
}
ctx := context.WithValue(r.Context(), "building", building)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (s *APIServer) getBuildings(w http.ResponseWriter, r *http.Request) error {
buildings, err := s.db.GetBuildings(0, 10)
if err != nil {
return err
}
total, err := s.db.TotalBuildings()
if err != nil {
return err
}
return render.Render(w, r, &types.MultipleBuildingResponse{
Response: &types.Response{
HTTPStatusCode: http.StatusOK,
},
Buildings: buildings,
Total: total,
})
}
func (s *APIServer) getBuilding(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
building, ok := ctx.Value("building").(*types.Building)
if !ok {
return render.Render(w, r, errUnprocessable)
}
return render.Render(w, r, &types.BuildingResponse{
Response: &types.Response{
HTTPStatusCode: http.StatusOK,
},
Building: building,
})
}