-
Notifications
You must be signed in to change notification settings - Fork 1
/
restore.go
88 lines (74 loc) 路 1.58 KB
/
restore.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
86
87
88
package action
import (
"context"
"errors"
"github.com/duxweb/go-fast/database"
"github.com/duxweb/go-fast/i18n"
"github.com/duxweb/go-fast/response"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
)
func (t *Resources[T]) Restore(ctx echo.Context) error {
var err error
if t.initFun != nil {
err = t.initFun(t, ctx)
if err != nil {
return err
}
}
id := ctx.Param("id")
err = t.restoreOne(ctx, id)
if err != nil {
return err
}
return response.Send(ctx, response.Data{
Message: i18n.Trans.Get("common.message.restore"),
})
}
func (t *Resources[T]) RestoreBefore(call ActionCallFun[T]) {
t.restoreBeforeFun = call
}
func (t *Resources[T]) RestoreAfter(call ActionCallFun[T]) {
t.restoreAfterFun = call
}
func (t *Resources[T]) restoreOne(ctx echo.Context, id string) error {
var model T
var err error
err = t.getOne(ctx, &model, id, nil)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return response.BusinessError(i18n.Trans.Get("common.message.emptyData"))
} else {
return err
}
}
tx := database.Gorm().Begin()
if tx.Error != nil {
return tx.Error
}
c := context.WithValue(context.Background(), "tx", tx)
if t.restoreBeforeFun != nil {
err = t.restoreBeforeFun(c, &model)
if err != nil {
tx.Rollback()
return err
}
}
err = tx.Model(&model).Unscoped().Update("deleted_at", nil).Error
if err != nil {
tx.Rollback()
return err
}
if t.restoreAfterFun != nil {
err = t.restoreAfterFun(c, &model)
if err != nil {
tx.Rollback()
return err
}
}
err = tx.Commit().Error
if err != nil {
return err
}
return nil
}