-
Notifications
You must be signed in to change notification settings - Fork 4
/
createProduct.go
60 lines (53 loc) · 1.68 KB
/
createProduct.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
package handler
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/log"
"github.com/sebajax/go-vertical-slice-architecture/internal/product"
"github.com/sebajax/go-vertical-slice-architecture/internal/product/service"
"github.com/sebajax/go-vertical-slice-architecture/pkg/apperror"
"github.com/sebajax/go-vertical-slice-architecture/pkg/message"
"github.com/sebajax/go-vertical-slice-architecture/pkg/validate"
)
// Body request schema for CreateProduct
type ProductSchema struct {
Name string `json:"name" validate:"required,min=5"`
Sku string `json:"sku" validate:"required,min=8"`
Category string `json:"category" validate:"required,min=5"`
Price float64 `json:"price" validate:"required"`
}
// Creates a new product into the database
func CreateProduct(s *service.CreateProductService) fiber.Handler {
return func(c *fiber.Ctx) error {
// Get body request
var body ProductSchema
// Validate the body
err := c.BodyParser(&body)
if err != nil {
// Map the error and response via the middleware
log.Error(err)
return err
}
// Validate schema
serr, err := validate.Validate(body)
if err != nil {
log.Error(serr)
return apperror.BadRequest(serr)
}
// No schema errores then map body to domain
p := &product.Product{
Name: body.Name,
Sku: body.Sku,
Category: product.ParseProductCategory(body.Category),
Price: body.Price,
}
// Execute the service
result, err := s.CreateProduct(p)
if err != nil {
// if service response an error return via the middleware
log.Error(err)
return err
}
// Success execution
return c.Status(fiber.StatusCreated).JSON(message.SuccessResponse(&result))
}
}