-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbatch_update.go
85 lines (67 loc) · 1.44 KB
/
batch_update.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package cosy
import (
"github.com/gin-gonic/gin"
"github.com/uozi-tech/cosy/map2struct"
"github.com/uozi-tech/cosy/model"
"net/http"
)
type batchUpdateStruct[T any] struct {
IDs []string `json:"ids"`
Data T `json:"data"`
}
func (c *Ctx[T]) BatchModify() {
if c.abort {
return
}
errs := validateBatchUpdate(c)
if len(errs) > 0 {
c.JSON(http.StatusNotAcceptable, NewValidateError(errs))
return
}
if c.abort {
return
}
db := model.UseDB()
c.applyGormScopes(db)
if c.beforeDecodeHook() {
return
}
resolvedModel := model.GetResolvedModel[T]()
for k := range c.Payload["data"].(map[string]interface{}) {
// check if the field is allowed to be batch updated
if _, ok := resolvedModel.Fields[k]; !ok ||
!resolvedModel.Fields[k].CosyTag.GetBatch() {
continue
}
c.AddSelectedFields(k)
}
var batchUpdate batchUpdateStruct[T]
err := map2struct.WeakDecode(c.Payload, &batchUpdate)
if err != nil {
errHandler(c.Context, err)
return
}
c.Model = batchUpdate.Data
c.BatchEffectedIDs = batchUpdate.IDs
if c.beforeExecuteHook() {
return
}
if c.abort {
return
}
if c.table != "" {
db = db.Table(c.table, c.tableArgs...)
}
err = db.Model(&c.Model).Where(c.itemKey+" IN ?", c.BatchEffectedIDs).
Select(c.GetSelectedFields()).Updates(&c.Model).Error
if err != nil {
errHandler(c.Context, err)
return
}
if c.executedHook() {
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}