Skip to content

Commit 6c023c4

Browse files
committed
add CreateProduct method to ProductRepository for product creation
1 parent 3ef7ee0 commit 6c023c4

File tree

4 files changed

+53
-0
lines changed

4 files changed

+53
-0
lines changed

cmd/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ func main() {
3131
})
3232

3333
server.GET("/products", ProductController.GetProducts)
34+
server.POST("/product", ProductController.CreateProduct)
3435

3536
server.Run(":8000")
3637

controller/product_controller.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package controller
22

33
import (
4+
"api-go/model"
45
"api-go/usecase"
56
"net/http"
67

@@ -26,3 +27,21 @@ func (p *productController) GetProducts(ctx *gin.Context) {
2627

2728
ctx.JSON(http.StatusOK, products)
2829
}
30+
31+
func (p *productController) CreateProduct(ctx *gin.Context) {
32+
33+
var product model.Product
34+
err := ctx.BindJSON(&product)
35+
if err != nil {
36+
ctx.JSON(http.StatusBadRequest, err)
37+
return
38+
}
39+
40+
insertedProduct, err := p.productUseCase.CreateProduct(product)
41+
if err != nil {
42+
ctx.JSON(http.StatusInternalServerError, err)
43+
return
44+
}
45+
46+
ctx.JSON(http.StatusCreated, insertedProduct)
47+
}

repository/product_repository.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,24 @@ func (pr *ProductRepository) GetProducts() ([]model.Product, error) {
4545

4646
return productList, nil
4747
}
48+
49+
func (pr *ProductRepository) CreateProduct(product model.Product) (int, error) {
50+
51+
var id int
52+
query, err := pr.connection.Prepare("INSERT INTO product" +
53+
"(product_name, price)" +
54+
"VALUES($1, $2) RETURNING id")
55+
if err != nil {
56+
fmt.Println(err)
57+
return 0, err
58+
}
59+
60+
err = query.QueryRow(product.Name, product.Price).Scan(&id)
61+
if err != nil {
62+
fmt.Println(err)
63+
return 0, err
64+
}
65+
66+
query.Close()
67+
return id, nil
68+
}

usecase/product_usecase.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,15 @@ func NewProductUseCase(repo repository.ProductRepository) *ProductUseCase {
1818
func (pu *ProductUseCase) GetProducts() ([]model.Product, error) {
1919
return pu.repository.GetProducts()
2020
}
21+
22+
func (pu *ProductUseCase) CreateProduct(product model.Product) (model.Product, error) {
23+
24+
productId, err := pu.repository.CreateProduct(product)
25+
if err != nil {
26+
return model.Product{}, err
27+
}
28+
29+
product.ID = productId
30+
31+
return product, nil
32+
}

0 commit comments

Comments
 (0)