-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcartController.js
96 lines (77 loc) · 2.29 KB
/
cartController.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const { removeFromInventory } = require('./inventoryController');
const { db } = require('./dbConnection');
const logger = require('./logger');
const addItemToCart = async (username, item) => {
await removeFromInventory(item) ;
const user = await db
.select()
.from('users')
.where({ username })
.first();
if (!user) {
const userNotFound = new Error('User not found');
userNotFound.code = 404;
throw userNotFound;
}
const itemEntry = await db
.select()
.from('carts_items')
.where({ userId: user.id, itemName: item })
.first();
if (itemEntry && itemEntry.quantity + 1 > 3) {
const limitError = new Error("Max 3 units of one particular item in your cart");
limitError.code = 400;
throw limitError;
}
if (itemEntry) {
await db('carts_items')
.increment('quantity')
.update({ updatedAt: new Date().toISOString() })
.where({
userId: itemEntry.userId,
itemName: item
});
} else {
await db('carts_items')
.insert({
userId: user.id,
itemName: item,
quantity: 1,
updatedAt: new Date().toISOString()
});
}
logger.log(`${item} has been added to ${username} cart.`);
return db
.select('itemName', 'quantity')
.from('carts_items')
.where({ userId: user.id });
};
const hoursInMs = hours => 1000 * 60 * 60 * hours;
const removeStaleItems = async () => {
const FOUR_HOURS_AGO = new Date(
Date.now() - hoursInMs(4)
).toISOString();
const staleItems = await db
.select()
.from('carts_items')
.where("updatedAt", "<", FOUR_HOURS_AGO );
if (staleItems.length === 0) return null;
const inventoryUpdates = staleItems.map(staleItem => {
db('inventory')
.increment("quantity", staleItem.quantity)
.where({ itemName: staleItem.itemName });
});
await Promise.all(inventoryUpdates);
const staleItemsTuples = staleItems.map( staleItem => [staleItem.itemName, staleItem.userId]);
await db('carts_items')
.del()
.whereIn(["itemName", "userId"], staleItemsTuples)
}
const monitorStaleItems = () => setInterval(
removeStaleItems,
hoursInMs(2)
);
module.exports = {
addItemToCart,
monitorStaleItems
};