-
Notifications
You must be signed in to change notification settings - Fork 1
/
memo_http.go
97 lines (84 loc) · 2.15 KB
/
memo_http.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
94
95
96
97
package handler
import (
"context"
"memoapi/memo"
"memoapi/model"
"net/http"
"strconv"
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
)
// MemoHTTPHandler represents memo http handler.
type MemoHTTPHandler struct {
usecase memo.Usecase
}
// NewMemoHTTPHandler returns new instance of MemoHTTPHandler.
func NewMemoHTTPHandler(usecase memo.Usecase) *MemoHTTPHandler {
return &MemoHTTPHandler{usecase: usecase}
}
// HandleCreateMemo handles create a memo.
func (h *MemoHTTPHandler) HandleCreateMemo(c echo.Context) error {
memo := model.Memo{}
if err := c.Bind(&memo); err != nil {
return c.JSON(http.StatusUnprocessableEntity, &Response{
Message: err.Error(),
Data: nil,
})
}
if err := h.usecase.CreateMemo(context.Background(), &memo); err != nil {
statusCode := http.StatusBadRequest
if _, ok := err.(validator.ValidationErrors); ok {
statusCode = http.StatusBadRequest
}
return c.JSON(statusCode, &Response{
Message: err.Error(),
Data: nil,
})
}
return c.JSON(http.StatusCreated, &Response{
Message: "success",
Data: memo,
})
}
// HandleGetMemoByID handles get memo by id.
func (h *MemoHTTPHandler) HandleGetMemoByID(c echo.Context) error {
memoIDStr := c.Param("memo_id")
id, err := strconv.Atoi(memoIDStr)
if err != nil {
return c.JSON(http.StatusNotFound, &Response{
Message: "memo is not found",
Data: nil,
})
}
memo, err := h.usecase.GetMemoByID(context.Background(), id)
if err != nil {
return c.JSON(http.StatusInternalServerError, &Response{
Message: err.Error(),
Data: nil,
})
}
if memo == nil {
return c.JSON(http.StatusNotFound, &Response{
Message: "memo is not found",
Data: nil,
})
}
return c.JSON(http.StatusOK, &Response{
Message: "success",
Data: memo,
})
}
// HandleGetAllMemo handles get all memos.
func (h *MemoHTTPHandler) HandleGetAllMemo(c echo.Context) error {
res, err := h.usecase.GetAllMemo(context.Background())
if err != nil {
return c.JSON(http.StatusInternalServerError, &Response{
Message: err.Error(),
Data: nil,
})
}
return c.JSON(http.StatusOK, &Response{
Message: "success",
Data: res,
})
}