-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler_create.go
77 lines (68 loc) · 1.88 KB
/
handler_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
71
72
73
74
75
76
77
package meta_gin
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type CreateHandler[M Model, ReqDTO any, ResDTO any] struct {
DB *gorm.DB
DTOHandler DTOHandler[M, ReqDTO, ResDTO]
Service *Service[M]
ServiceExecuters []ServiceExecutor[M]
}
func NewCreateHandler[M Model, ReqDTO any, ResDTO any](
db *gorm.DB,
service *Service[M],
dtoHandler DTOHandler[M, ReqDTO, ResDTO],
) *CreateHandler[M, ReqDTO, ResDTO] {
return &CreateHandler[M, ReqDTO, ResDTO]{
DB: db,
Service: service,
DTOHandler: dtoHandler,
}
}
func (h *CreateHandler[M, ReqDTO, ResDTO]) AddServiceExecuter(
serviceExecuter ServiceExecutor[M],
) {
h.ServiceExecuters = append(h.ServiceExecuters, serviceExecuter)
}
func (h *CreateHandler[M, ReqDTO, ResDTO]) GetName() string {
return "create_handler"
}
func (h *CreateHandler[M, ReqDTO, ResDTO]) Method() string {
return http.MethodPost
}
func (h *CreateHandler[M, ReqDTO, ResDTO]) Handlers() map[string]gin.HandlerFunc {
return map[string]gin.HandlerFunc{
"/": h.Create(),
}
}
func (h *CreateHandler[M, ReqDTO, ResDTO]) Create() 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)
for _, service := range h.ServiceExecuters {
if service != nil {
m, err := service.Execute(c, &model)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
model = *m
}
}
m, err := h.Service.Create(model)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
resDTO := h.DTOHandler.FromModel(m)
ctx.JSON(http.StatusCreated, gin.H{"data": resDTO})
}
}