in inventory-service/spanner/main.go [110:167]
func updateInventoryItem(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
if r.URL.Path != "/updateInventoryItem" {
http.NotFound(w, r)
return
}
switch r.Method {
case "GET":
w.Write([]byte("Please POST the following format for data: [{'itemID': int,'inventoryChange': int}]"))
return
case "OPTIONS":
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.WriteHeader((http.StatusOK))
return
case "POST":
(w).Header().Set("content-type", "application/json")
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
il := []struct {
ItemID int `json:"itemID"`
InventoryChange int `json:"inventoryChange"`
}{}
err := d.Decode(&il)
if err != nil {
log.Print(err)
return
}
// In production code you should check and sanatize data. This is a demo however
log.Print(il)
// This should be a global variable since it's used more than once
inventoryHistoryColumns := []string{
"ItemRowID",
"ItemID",
"inventoryChange",
"timeStamp"}
m := []*spanner.Mutation{}
for _, element := range il {
m = append(m, spanner.Insert(
"inventoryHistory",
inventoryHistoryColumns,
[]interface{}{uuid.New().String(), element.ItemID, element.InventoryChange, time.Now()}))
}
_, err = dataClient.Apply(context.Background(), m)
if err != nil {
log.Print(err)
return
}
log.Print("Data added to database")
w.Write([]byte(http.StatusText(http.StatusOK)))
default:
w.WriteHeader(http.StatusNotImplemented)
w.Write([]byte(http.StatusText(http.StatusNotImplemented)))
}
}