-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathupdate.go
More file actions
94 lines (86 loc) · 2.37 KB
/
Copy pathupdate.go
File metadata and controls
94 lines (86 loc) · 2.37 KB
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
86
87
88
89
90
91
92
93
94
package cosy
import (
"net/http"
"reflect"
"github.com/gin-gonic/gin"
"github.com/uozi-tech/cosy/map2struct"
"gorm.io/gorm/clause"
)
func (c *Ctx[T]) SetNextHandler(handler gin.HandlerFunc) *Ctx[T] {
c.nextHandler = &handler
return c
}
func (c *Ctx[T]) Modify() {
NewProcessChain(c).
SetPrepare(func(ctx *Ctx[T]) {
c.ID = c.GetParamID()
modifyHook[T]()(c)
prepareHook(ctx)
}).
SetValidate(func(ctx *Ctx[T]) {
errs := c.validate()
if len(errs) > 0 {
c.JSON(http.StatusNotAcceptable, NewValidateError(errs))
c.Abort()
return
}
}).
SetBeforeDecode(func(ctx *Ctx[T]) {
tx := c.applyGormScopes(c.Tx)
if err := tx.First(&c.OriginModel, "id = ?", c.ID).Error; err != nil {
ctx.AbortWithError(err)
return
}
beforeDecodeHook(ctx)
}).
SetDecode(func(ctx *Ctx[T]) {
for k := range c.Payload {
// Map JSON / cosy json:* keys to GORM column names so Select() updates the right columns.
c.AddSelectedFields(c.resolveColumn(k))
}
if err := map2struct.WeakDecode(c.Payload, &c.Model); err != nil {
ctx.AbortWithError(err)
return
}
}).
SetBeforeExecute(beforeExecuteHook[T]).
SetGormAction(func(ctx *Ctx[T]) {
if c.table != "" {
c.Tx = c.Tx.Table(c.table, c.tableArgs...)
}
v := reflect.ValueOf(&c.Model).Elem()
idField := v.FieldByName("ID")
if idField.IsValid() && idField.CanSet() {
idValue := reflect.ValueOf(c.ID)
if idValue.Type().AssignableTo(idField.Type()) {
idField.Set(idValue)
} else if idValue.Type().ConvertibleTo(idField.Type()) {
idField.Set(idValue.Convert(idField.Type()))
}
}
// An empty selection would make GORM's Save fall back to "*" and
// overwrite every column with the zero-valued c.Model, so a body
// that carries no updatable field is rejected instead.
fields := c.GetSelectedFields()
if len(fields) == 0 {
abortEmptyPayload(c)
return
}
if err := c.Tx.Select(fields).Save(&c.Model).Error; err != nil {
ctx.AbortWithError(err)
return
}
tx := c.Tx.Preload(clause.Associations)
tx = c.resolvePreload(tx)
tx = c.resolveJoins(tx)
tx.Table(c.table, c.tableArgs...).First(&c.Model, "id = ?", c.ID)
}).
SetExecuted(executedHook[T]).
SetResponse(func(ctx *Ctx[T]) {
if c.nextHandler != nil {
(*c.nextHandler)(c.Context)
} else {
c.JSON(http.StatusOK, c.Model)
}
}).CreateOrModify()
}