-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcreate.go
70 lines (54 loc) · 1.07 KB
/
create.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
package cosy
import (
"github.com/uozi-tech/cosy/map2struct"
"github.com/uozi-tech/cosy/model"
"gorm.io/gorm/clause"
"net/http"
)
func (c *Ctx[T]) Create() {
errs := c.validate()
if len(errs) > 0 {
c.JSON(http.StatusNotAcceptable, NewValidateError(errs))
return
}
if c.abort {
return
}
db := model.UseDB()
if c.beforeDecodeHook() {
return
}
err := map2struct.WeakDecode(c.Payload, &c.Model)
if err != nil {
errHandler(c.Context, err)
return
}
if c.beforeExecuteHook() {
return
}
if c.skipAssociationsOnCreate {
err = db.Omit(clause.Associations).Create(&c.Model).Error
} else {
err = db.Create(&c.Model).Error
}
if err != nil {
errHandler(c.Context, err)
return
}
tx := db.Preload(clause.Associations)
tx = c.resolvePreload(tx)
tx = c.resolveJoins(tx)
tx.Table(c.table, c.tableArgs...).First(&c.Model)
if c.executedHook() {
return
}
if c.nextHandler != nil {
(*c.nextHandler)(c.Context)
} else {
c.JSON(http.StatusOK, c.Model)
}
}
func (c *Ctx[T]) WithAssociations() *Ctx[T] {
c.skipAssociationsOnCreate = false
return c
}