-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (70 loc) · 2.27 KB
/
index.js
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
// const EventEmitter = require("events");
// const stockData = require("./stock-list.json");
// class OrderProcessor extends EventEmitter {
// placeOrder(orderData) {
// const orderNumber = orderData[0].orderNumber;
// this.emit("PROCESSING_STARTED", orderNumber);
// let isValid = true;
// let errorObject = null;
// orderData[0].lineItems.forEach((lineItem) => {
// const matchingStock = stockData.find(
// (stockItem) => stockItem.id === lineItem.itemId
// );
// if (matchingStock.stock < lineItem.quantity) {
// isValid = false;
// errorObject = {
// orderNumber,
// itemId: lineItem.itemId,
// reason: "INSUFFICIENT_STOCK",
// };
// return;
// }
// });
// if (orderData[0].lineItems.length === 0) {
// isValid = false;
// errorObject = {
// orderNumber,
// reason: "LINEITEMS_EMPTY",
// };
// }
// if (isValid) {
// this.emit("PROCESSING_SUCCESS", orderNumber);
// } else {
// this.emit("PROCESSING_FAILED", errorObject);
// }
// }
// }
// module.exports = OrderProcessor;
const EventEmitter = require("events");
const stockData = require("./stock-list.json");
class OrderProcessor extends EventEmitter {
placeOrder(orderData) {
const orderNumber = orderData.orderNumber;
this.emit("PROCESSING_STARTED", orderNumber);
const lineItems = orderData.lineItems;
if (lineItems.length === 0) {
const failureData = {
orderNumber: orderNumber,
reason: "LINEITEMS_EMPTY",
};
this.emit("PROCESSING_FAILED", failureData);
return;
}
for (const item of lineItems) {
const itemId = item.itemId;
const requestedQuantity = item.quantity;
const matchingStock = stockData.find((s) => s.id === itemId).stock;
if (requestedQuantity > matchingStock) {
const failureData = {
orderNumber: orderNumber,
itemId: itemId,
reason: "INSUFFICIENT_STOCK",
};
this.emit("PROCESSING_FAILED", failureData);
return;
}
}
this.emit("PROCESSING_SUCCESS", orderNumber);
}
}
module.exports = OrderProcessor;