-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler_delete.go
93 lines (81 loc) · 2.28 KB
/
handler_delete.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
89
90
91
92
93
package meta_gin
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type DeleteHandler[M Model, ReqDTO any, ResDTO any] struct {
DB *gorm.DB
DTOHandler DTOHandler[M, ReqDTO, ResDTO]
Service *Service[M]
ServiceExecuters []ServiceExecutor[M]
}
func (h *DeleteHandler[M, ReqDTO, ResDTO]) AddServiceExecuter(
serviceExecuter ServiceExecutor[M],
) {
h.ServiceExecuters = append(h.ServiceExecuters, serviceExecuter)
}
func NewDeleteHandler[M Model, ReqDTO any, ResDTO any](
db *gorm.DB,
service *Service[M],
dtoHandler DTOHandler[M, ReqDTO, ResDTO],
) *DeleteHandler[M, ReqDTO, ResDTO] {
return &DeleteHandler[M, ReqDTO, ResDTO]{
DB: db,
Service: service,
DTOHandler: dtoHandler,
}
}
func (h *DeleteHandler[M, ReqDTO, ResDTO]) GetName() string {
return "delete_handler"
}
func (h *DeleteHandler[M, ReqDTO, ResDTO]) Method() string {
return http.MethodDelete
}
func (h *DeleteHandler[M, ReqDTO, ResDTO]) Handlers() map[string]gin.HandlerFunc {
return map[string]gin.HandlerFunc{
"/": h.Delete(),
"/:id": h.DeleteByID(),
}
}
func (h *DeleteHandler[M, ReqDTO, ResDTO]) DeleteByID() gin.HandlerFunc {
return func(ctx *gin.Context) {
id := ctx.Param("id")
c := context.WithValue(ctx.Request.Context(), resID, id)
for _, service := range h.ServiceExecuters {
if service != nil {
service.Execute(c, nil)
}
}
err := h.Service.DeleteByID(id)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "deleted"})
}
}
func (h *DeleteHandler[M, ReqDTO, ResDTO]) Delete(services ...ServiceExecutor[M]) gin.HandlerFunc {
return func(ctx *gin.Context) {
var dto ReqDTO
if err := ctx.ShouldBindJSON(&dto); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
model := h.DTOHandler.ToModel(dto)
c := context.WithValue(ctx.Request.Context(), dtoKey, dto)
c = context.WithValue(c, modelKey, model)
for _, service := range services {
if service != nil {
service.Execute(c, &model)
}
}
err := h.Service.Delete(model)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "deleted"})
}
}