updateSessionHandler updates the data of an existing session
(w http.ResponseWriter, r *http.Request)
| 112 | |
| 113 | // updateSessionHandler updates the data of an existing session |
| 114 | func updateSessionHandler(w http.ResponseWriter, r *http.Request) { |
| 115 | if db.Instance == nil { |
| 116 | jsonError(w, http.StatusBadRequest, errors.New("database offline")) |
| 117 | return |
| 118 | } |
| 119 | |
| 120 | id := mux.Vars(r)["id"] |
| 121 | |
| 122 | var body map[string]any |
| 123 | if err := json.NewDecoder(r.Body).Decode(&body); err != nil { |
| 124 | jsonError(w, http.StatusBadRequest, err) |
| 125 | return |
| 126 | } |
| 127 | |
| 128 | // only update fields present in the request; a null value clears the column |
| 129 | updates := map[string]any{} |
| 130 | if v, ok := body["vehicle"]; ok { |
| 131 | updates["vehicle"] = v |
| 132 | } |
| 133 | if v, ok := body["loadpoint"]; ok { |
| 134 | updates["loadpoint"] = v |
| 135 | } |
| 136 | if v, ok := body["odometer"]; ok { |
| 137 | updates["odometer"] = v |
| 138 | } |
| 139 | |
| 140 | if len(updates) == 0 { |
| 141 | jsonError(w, http.StatusBadRequest, errors.New("nothing to update")) |
| 142 | return |
| 143 | } |
| 144 | |
| 145 | if txn := db.Instance.Table("sessions").Where("id = ?", id).Updates(updates); txn.Error != nil { |
| 146 | jsonError(w, http.StatusBadRequest, txn.Error) |
| 147 | return |
| 148 | } |
| 149 | } |