-
Notifications
You must be signed in to change notification settings - Fork 0
/
create.go
48 lines (40 loc) · 1.41 KB
/
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
package customer_controller
import (
"context"
"net/http"
"time"
"github.com/taako-502/go-mongodb-sample/app/infrastructure"
"github.com/taako-502/go-mongodb-sample/app/infrastructure/customer_infrastructure"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
type NewCreate struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required"`
Address string `json:"address" validate:"required"`
}
func (cc CostumerController) Create(c echo.Context) error {
request := new(NewCreate)
if err := c.Bind(request); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
// コンテキストを設定
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
dbm, err := infrastructure.NewMongoDBManager(ctx, cc.ConnectionString)
if err != nil {
return errors.Wrap(err, "NewMongoDBManager")
}
defer dbm.Client.Disconnect(ctx)
ci := customer_infrastructure.NewCustomerRepository(ctx, dbm.Client.Database(cc.DBName))
dto := customer_infrastructure.NewCustomerDTO(request.Name, request.Email, request.Address)
customer, err := ci.Create(dto)
if err != nil {
if errors.Is(err, customer_infrastructure.ErrCustomerDuplicate) {
return echo.NewHTTPError(http.StatusConflict, err.Error())
} else {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
}
return c.JSON(http.StatusOK, customer)
}