2022-01-25 07:25:43 +00:00
|
|
|
package databag
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"databag/internal/store"
|
|
|
|
)
|
|
|
|
|
|
|
|
func UpdateGroup(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
|
|
|
account, code, err := BearerAppToken(r, false)
|
|
|
|
if err != nil {
|
|
|
|
ErrResponse(w, code, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
params := mux.Vars(r)
|
|
|
|
groupId := params["groupId"]
|
|
|
|
|
|
|
|
var subject Subject
|
|
|
|
if err := ParseRequest(r, w, &subject); err != nil {
|
|
|
|
ErrResponse(w, http.StatusBadRequest, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// load specified group
|
2022-02-03 07:48:17 +00:00
|
|
|
var slot store.GroupSlot
|
|
|
|
if err := store.DB.Preload("Group.GroupData").Where("account_id = ? AND group_slot_id = ?", account.ID, groupId).First(&slot).Error; err != nil {
|
2022-01-25 07:25:43 +00:00
|
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
|
|
ErrResponse(w, http.StatusInternalServerError, err)
|
|
|
|
} else {
|
|
|
|
ErrResponse(w, http.StatusNotFound, err)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2022-02-03 07:48:17 +00:00
|
|
|
if slot.Group == nil {
|
|
|
|
ErrResponse(w, http.StatusNotFound, errors.New("referenced deleted group"))
|
|
|
|
return
|
|
|
|
}
|
2022-01-25 07:25:43 +00:00
|
|
|
|
|
|
|
// update specified group
|
2022-02-03 07:48:17 +00:00
|
|
|
slot.Revision = account.GroupRevision + 1
|
|
|
|
slot.Group.DataType = subject.DataType
|
|
|
|
slot.Group.GroupData.Data = subject.Data
|
2022-01-25 07:25:43 +00:00
|
|
|
err = store.DB.Transaction(func(tx *gorm.DB) error {
|
2022-02-03 07:48:17 +00:00
|
|
|
if res := tx.Save(&slot.Group.GroupData).Error; res != nil {
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
if res := tx.Save(&slot.Group).Error; res != nil {
|
2022-02-02 18:55:45 +00:00
|
|
|
return res
|
|
|
|
}
|
2022-02-03 07:48:17 +00:00
|
|
|
if res := tx.Save(&slot).Error; res != nil {
|
2022-01-25 07:25:43 +00:00
|
|
|
return res
|
|
|
|
}
|
2022-02-03 07:48:17 +00:00
|
|
|
if res := tx.Model(&account).Update("group_revision", account.GroupRevision + 1).Error; res != nil {
|
2022-01-25 07:25:43 +00:00
|
|
|
return res
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
ErrResponse(w, http.StatusInternalServerError, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
SetStatus(account)
|
2022-02-03 07:48:17 +00:00
|
|
|
WriteResponse(w, getGroupModel(&slot))
|
2022-01-25 07:25:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|