/
update_customer.go
63 lines (53 loc) · 1.65 KB
/
update_customer.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
package controllers
import (
"github.com/bostaurus/jsend"
"github.com/labstack/echo"
"github.com/labstack/gommon/log"
"github.com/ricardojonathanromero/go-jenkins/models"
"go.mongodb.org/mongo-driver/bson/primitive"
"gopkg.in/go-playground/validator.v9"
"net/http"
)
// HandleUpdateCustomer update the customer info
func (c *Controller) HandleUpdateCustomer(ctx echo.Context) error {
customerID := ctx.Param("customerID")
id, err := primitive.ObjectIDFromHex(customerID)
if err != nil {
log.Errorf("Error (%v)", err)
return ctx.JSON(http.StatusBadRequest, jsend.Fail(&models.Error{
Code: "invalid_request_params",
Message: "The customerID must be a valid ID",
Source: "api.validations.path",
}))
}
// set up validator function
ctx.Echo().Validator = &models.Validator{Validator: validator.New()}
// define struct
payload := new(models.Customer)
// validating request has a body
if err := ctx.Bind(payload); err != nil {
log.Errorf("Error (%v)", err)
return ctx.JSON(http.StatusBadRequest, jsend.Fail(&models.Error{
Code: "bad_request",
Message: err.Error(),
Source: "api.validations.body",
}))
}
// validate body request has required fields
if err := ctx.Validate(payload); err != nil {
return ctx.JSON(http.StatusBadRequest, jsend.Fail(&models.Error{
Code: "invalid_param_values",
Message: err.Error(),
Source: "api.validations.payload",
}))
}
err = editCustomer(id, payload)
if err != nil {
return ctx.JSON(http.StatusConflict, jsend.Fail(&models.Error{
Code: "customer_not_updated",
Message: err.Error(),
Source: "api.customers",
}))
}
return ctx.NoContent(http.StatusAccepted)
}