-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
51 lines (41 loc) · 771 Bytes
/
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
package crud
import (
"net/http"
"github.com/dmcalpin/go-cms/db"
"github.com/gin-gonic/gin"
)
func (crud *CRUD[T]) Update(c *gin.Context) {
key, err := crud.decodeKeyParam(&c.Params)
if err != nil {
crud.logAndWriteError(c, err)
return
}
var t T
entity := t.New(key)
err = db.Get(c, entity)
if err != nil {
crud.logAndWriteError(c, err)
return
}
// Update the entity
// Parse JSON
input := t.New(nil)
err = c.Bind(input)
if err != nil {
crud.logAndWriteError(c, err)
return
}
entity.Patch(input)
err = entity.Validate()
if err != nil {
crud.logAndWriteError(c, err)
return
}
entity.SetUpdatedAt()
err = db.SaveAndGet(c, entity)
if err != nil {
crud.logAndWriteError(c, err)
return
}
c.JSON(http.StatusOK, entity)
}