-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathcreate.go
More file actions
48 lines (41 loc) · 1.22 KB
/
create.go
File metadata and controls
48 lines (41 loc) · 1.22 KB
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
package courses
import (
"errors"
"net/http"
mooc "github.com/CodelyTV/go-hexagonal_http_api-course/04-03-command-bus/internal"
"github.com/CodelyTV/go-hexagonal_http_api-course/04-03-command-bus/internal/creating"
"github.com/CodelyTV/go-hexagonal_http_api-course/04-03-command-bus/kit/bus"
"github.com/gin-gonic/gin"
)
type createRequest struct {
ID string `json:"id" binding:"required"`
Name string `json:"name" binding:"required"`
Duration string `json:"duration" binding:"required"`
}
// CreateHandler returns an HTTP handler for courses creation.
func CreateHandler(bus bus.Bus) gin.HandlerFunc {
return func(ctx *gin.Context) {
var req createRequest
if err := ctx.BindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, err.Error())
return
}
err := bus.DispatchCommand(ctx, creating.NewCourseCommand(
req.ID,
req.Name,
req.Duration,
))
if err != nil {
switch {
case errors.Is(err, mooc.ErrInvalidCourseID),
errors.Is(err, mooc.ErrEmptyCourseName), errors.Is(err, mooc.ErrInvalidCourseID):
ctx.JSON(http.StatusBadRequest, err.Error())
return
default:
ctx.JSON(http.StatusInternalServerError, err.Error())
return
}
}
ctx.Status(http.StatusCreated)
}
}