Skip to content

Commit d43c6aa

Browse files
committed
post shipments through HTTP
1 parent 2d33961 commit d43c6aa

File tree

5 files changed

+78
-13
lines changed

5 files changed

+78
-13
lines changed

warehouse-client/main.js

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,36 @@
1-
const BASE_URL = "http://localhost:8082/";
1+
const BASE_URL = "http://localhost:8082";
22
async function fetchData() {
33
const res = await fetch(`${BASE_URL}/api/shipment`);
44
const shipments = await res.json();
55
return shipments;
66
}
77

8+
async function shipCart(cartId) {
9+
const res = await fetch(`${BASE_URL}/api/shipment`, {
10+
method: "POST",
11+
body: JSON.stringify({ cartId }),
12+
});
13+
if (res.status !== 200) {
14+
throw new Error("Something went wrong!");
15+
}
16+
}
17+
818
function generateBtnId(cartId) {
919
return `btn-${cartId}`;
1020
}
1121

22+
function generateBtnHandler(cartId) {
23+
return async () => {
24+
try {
25+
await shipCart(cartId);
26+
main();
27+
} catch (err) {
28+
console.log(err);
29+
alert(err);
30+
}
31+
};
32+
}
33+
1234
function renderData(rows) {
1335
document.getElementById("root").innerHTML = `<div class="grid-container">
1436
${rows
@@ -19,11 +41,6 @@ ${rows
1941
paid,
2042
} = row;
2143
22-
// TODO: do this from the backend
23-
if (shipped) {
24-
return "";
25-
}
26-
2744
return `
2845
<div id=${cartId} class="grid-item">
2946
<h2><code>${cartId}</code>\t${paid ? "Paid" : "Pending"}</h2>
@@ -35,7 +52,7 @@ ${rows
3552
<ul>
3653
${items
3754
.map(
38-
({ book, qty }) =>
55+
({ book, Qty: qty }) =>
3956
`<li>${book.title} - ${book.author} - ${qty}</li>`
4057
)
4158
.join("")}
@@ -48,17 +65,17 @@ ${rows
4865
})
4966
.join("")}
5067
</div>`;
68+
return Promise.resolve();
5169
}
5270

5371
function attachBtnHandlers(rows) {
54-
const buttonIds = rows.map((row) => {
72+
rows.forEach((row) => {
5573
const {
5674
cart: { cartId },
5775
} = row;
58-
return generateBtnId(cartId);
59-
});
60-
buttonIds.forEach((btnId) => {
61-
document.getElementById(btnId).onclick = () => alert(`${btnId} Clicked`);
76+
const curBtnId = generateBtnId(cartId);
77+
const curBtnHandler = generateBtnHandler(cartId);
78+
document.getElementById(curBtnId).onclick = curBtnHandler;
6279
});
6380
}
6481

warehouse-server/dto/shipment.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package dto
2+
3+
import "go.mongodb.org/mongo-driver/bson/primitive"
4+
5+
type PostShipment struct {
6+
CartID primitive.ObjectID `bson:"_id,omitempty" json:"cartId"`
7+
}

warehouse-server/handler/warehouse.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"log"
66
"net/http"
77

8+
localDTO "github.com/mtanzim/event-driven-bookstore/warehouse-server/dto"
89
service "github.com/mtanzim/event-driven-bookstore/warehouse-server/service"
910
)
1011

@@ -26,3 +27,20 @@ func (h ShipmentHandler) GetPendingShipments(w http.ResponseWriter, r *http.Requ
2627
}
2728
json.NewEncoder(w).Encode(pendingShipments)
2829
}
30+
31+
func (h ShipmentHandler) PostPendingShipemt(w http.ResponseWriter, r *http.Request) {
32+
w.Header().Set("Content-Type", "application/json")
33+
var cart localDTO.PostShipment
34+
if err := json.NewDecoder(r.Body).Decode(&cart); err != nil {
35+
log.Println(err)
36+
http.Error(w, "Cannot process shipment", http.StatusBadRequest)
37+
return
38+
}
39+
postedShipment, err := h.service.PostPendingShipemt(&cart)
40+
if err != nil {
41+
log.Println(err)
42+
http.Error(w, "Cannot update shipment", http.StatusInternalServerError)
43+
return
44+
}
45+
json.NewEncoder(w).Encode(postedShipment)
46+
}

warehouse-server/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ func main() {
5454
r := mux.NewRouter()
5555
port := os.Getenv("REST_PORT")
5656
r.HandleFunc("/api/shipment", shipmentHandler.GetPendingShipments).Methods(http.MethodGet, http.MethodOptions)
57+
r.HandleFunc("/api/shipment", shipmentHandler.PostPendingShipemt).Methods(http.MethodPost, http.MethodOptions)
5758
r.Use(loggingMiddleware)
5859
// TODO: fix this
5960
rWithCORS := cors.Default().Handler(r)

warehouse-server/service/shipment.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@ package service
33
import (
44
"context"
55
"encoding/json"
6+
"errors"
67
"log"
78
"time"
89

910
dto "github.com/mtanzim/event-driven-bookstore/common-server/dto"
11+
localDTO "github.com/mtanzim/event-driven-bookstore/warehouse-server/dto"
1012
"go.mongodb.org/mongo-driver/bson"
1113
"go.mongodb.org/mongo-driver/mongo"
1214
"gopkg.in/confluentinc/confluent-kafka-go.v1/kafka"
@@ -26,7 +28,8 @@ func (s ShipmentService) GetPendingShipments() ([]dto.CartWarehouse, error) {
2628
defer cancel()
2729

2830
var data []dto.CartWarehouse
29-
cursor, err := s.collection.Find(ctx, bson.M{}, nil)
31+
filter := bson.M{"shipped": false}
32+
cursor, err := s.collection.Find(ctx, filter, nil)
3033
if err != nil {
3134
return nil, err
3235

@@ -38,6 +41,25 @@ func (s ShipmentService) GetPendingShipments() ([]dto.CartWarehouse, error) {
3841

3942
}
4043

44+
func (s ShipmentService) PostPendingShipemt(cart *localDTO.PostShipment) (*localDTO.PostShipment, error) {
45+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
46+
defer cancel()
47+
48+
filter := bson.M{"_id": cart.CartID}
49+
update := bson.D{{"$set", bson.D{{"shipped", true}}}}
50+
51+
updateRes, updateErr := s.collection.UpdateOne(ctx, filter, update)
52+
if updateErr != nil {
53+
return nil, updateErr
54+
}
55+
if updateRes.ModifiedCount == 1 || updateRes.UpsertedCount == 1 {
56+
log.Println("Successfully shipped cart:", cart.CartID)
57+
return cart, nil
58+
}
59+
return nil, errors.New("Something went wrong.")
60+
61+
}
62+
4163
func (s ShipmentService) ConsumeMessages() {
4264
// TODO: is this idiomatic :/
4365
s.warehouseService.ConsumeMessages(s.processShipmentRequest)

0 commit comments

Comments
 (0)