This repository has been archived by the owner on Oct 20, 2020. It is now read-only.
/
api_products.go
154 lines (141 loc) · 4.1 KB
/
api_products.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/*
* ExCommerce
*
* ExCommerce is an example commerce system.
*
* API version: beta
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"unicode/utf8"
"github.com/Teelevision/excommerce/authentication"
"github.com/Teelevision/excommerce/controller"
"github.com/Teelevision/excommerce/model"
"github.com/gorilla/mux"
)
var _ Router = (*ProductsAPI)(nil)
// A ProductsAPI binds http requests to an api service and writes the service results to the http response
type ProductsAPI struct {
Authenticator *authentication.Authenticator
ProductController *controller.Product
}
// Routes returns all of the api route for the ProductsApiController
func (c *ProductsAPI) Routes() Routes {
return Routes{
{
Name: "GetAllProducts",
Method: "GET",
Path: "/beta/products",
HandlerFunc: c.GetAllProducts,
},
{
Name: "StoreCouponForProduct",
Method: "PUT",
Path: "/beta/products/{productId}/coupons/{couponCode}",
HandlerFunc: c.Authenticator.HandlerFunc(c.StoreCouponForProduct),
},
}
}
// GetAllProducts - Get all products
func (c *ProductsAPI) GetAllProducts(w http.ResponseWriter, r *http.Request) {
products, err := c.ProductController.GetAll(r.Context())
switch {
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
w.WriteHeader(499) // client closed request
case err == nil:
result := make([]Product, len(products))
for i, product := range products {
result[i].ID = product.ID
result[i].Name = product.Name
result[i].Price = float32(product.Price) / 100
}
EncodeJSONResponse(result, nil, w)
default:
panic(err)
}
}
// StoreCouponForProduct - Create product coupon
func (c *ProductsAPI) StoreCouponForProduct(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// check that the user is the admin
user := authentication.AuthenticatedUser(ctx)
if user.Name != "admin" {
w.WriteHeader(http.StatusForbidden) // 403
return
}
// input
params := mux.Vars(r)
productID := params["productId"]
couponCode := strings.ToLower(params["couponCode"])
coupon := &Coupon{}
if err := json.NewDecoder(r.Body).Decode(&coupon); err != nil {
w.WriteHeader(500)
return
}
// validation
if !uuidPattern.Match([]byte(productID)) {
invalidInput("The productId of the path is not a UUID.", uuidPattern.String(), w)
return
}
if l := utf8.RuneCountInString(couponCode); l < 6 || l > 40 {
invalidInput("The coupon code must be 6 to 40 characters long.", "", w)
return
}
if l := utf8.RuneCountInString(coupon.Name); l < 1 || l > 100 {
failValidation("The name must be 1 to 100 characters long.", "/name", w)
return
}
if coupon.Discount < 1 || coupon.Discount > 100 {
failValidation("The discount must be any integer from 1 to 100.", "/discount", w)
return
}
// convert to internal model
couponInput := model.Coupon{
Code: couponCode,
ProductID: productID,
Name: coupon.Name,
Discount: int(coupon.Discount),
ExpiresAt: coupon.ExpiresAt,
}
// load product
product, err := c.ProductController.Get(ctx, couponInput.ProductID)
switch {
case errors.Is(err, controller.ErrNotFound):
w.WriteHeader(http.StatusNotFound) // 404
return
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
w.WriteHeader(499) // client closed request
return
case err == nil:
couponInput.Product = product
default:
panic(err)
}
// action
couponOutput, err := c.ProductController.SaveCoupon(ctx, &couponInput)
switch {
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
w.WriteHeader(499) // client closed request
case err == nil:
EncodeJSONResponse(&Coupon{
Code: couponOutput.Code,
Name: couponOutput.Name,
Discount: int32(couponOutput.Discount),
ExpiresAt: couponOutput.ExpiresAt.UTC().Truncate(time.Second),
Product: Product{
ID: couponOutput.Product.ID,
Name: couponOutput.Product.Name,
Price: float32(couponOutput.Product.Price) / 100,
},
}, nil, w)
default:
panic(err)
}
}