From 6bfb49512d1bda7cbc108061bc6213d3fcb09c5f Mon Sep 17 00:00:00 2001 From: SowinskiBraeden Date: Mon, 14 Nov 2022 08:37:33 -0800 Subject: [PATCH] get bookings by cow function --- api/handlers/api.go | 1 + api/handlers/cow.go | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/api/handlers/api.go b/api/handlers/api.go index e9d42cb..22265db 100644 --- a/api/handlers/api.go +++ b/api/handlers/api.go @@ -44,6 +44,7 @@ func (a *App) New() *mux.Router { apiCreate.Handle("/cows/update/{cow_id}", api.Middleware(http.HandlerFunc(cow.UpdateCowHandler))).Methods("POST") // Update Cow by Object ID apiCreate.Handle("/cows/add_device/{cow_id}", api.Middleware(http.HandlerFunc(cow.AddDeviceHandler))).Methods("POST") // Add Device to cow device list apiCreate.Handle("/cows/get_devices/{cow_id}", api.Middleware(http.HandlerFunc(device.GetChildDevices))).Methods("POST") // Returns a list of devices from a given Cow obj + apiCreate.Handle("cows/bookings/{cow_id}", api.Middleware(http.HandlerFunc(cow.GetBookingsHandler))).Methods("GET") // Returns all bookings for a given cow apiCreate.Handle("/device/{device_id}", api.Middleware(http.HandlerFunc(device.DeviceByIDHandler))).Methods("GET") // By Object ID not Device Name apiCreate.Handle("/devices", api.Middleware(http.HandlerFunc(device.DeviceHandler))).Methods("GET") // Returns all devices diff --git a/api/handlers/cow.go b/api/handlers/cow.go index e37e49e..f223f46 100644 --- a/api/handlers/cow.go +++ b/api/handlers/cow.go @@ -222,3 +222,27 @@ func (c Cow) AddDeviceHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write(b) } + +func (c Cow) GetBookingsHandler(w http.ResponseWriter, r *http.Request) { + cowID := mux.Vars(r)["cow_id"] + + cID, err := primitive.ObjectIDFromHex(cowID) + if err != nil { + config.ErrorStatus("failed to get objectID from Hex", http.StatusBadRequest, w, err) + return + } + + dbResp, err := c.DB.FindOne(context.Background(), bson.M{"_id": cID}) + if err != nil { + config.ErrorStatus("failed to get cow by ID", http.StatusNotFound, w, err) + return + } + + b, err := json.Marshal(models.UserResponse{Status: http.StatusOK, Message: "success", Data: map[string]interface{}{"result": dbResp.Details.Bookings}}) + if err != nil { + config.ErrorStatus("failed to marshal response", http.StatusInternalServerError, w, err) + return + } + w.WriteHeader(http.StatusOK) + w.Write(b) +}