-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (62 loc) · 2.12 KB
/
index.js
File metadata and controls
76 lines (62 loc) · 2.12 KB
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
const express = require('express');
const Redis = require('ioredis');
const amqp = require('amqplib');
const app = express();
const redis = new Redis();
app.use(express.json());
// Global variables for RabbitMQ
let channel, connection;
async function connectQueue(){
try { connection = await amqp.connect('amqp://localhost');
channel = await connection.createChannel();
// Create a specific box named 'orders' to store our messages
await channel.assertQueue('orders');
console.log('✅ Connected to RabbitMQ');}
catch (err) {
console.log('Queue Error:', error);
}
}
// Start the connection immediately
connectQueue();
// 1. Initialize the Sale (Resets the stock)
app.post('/init',async (req,res)=>{
await redis.set('iphone_stock',100);
res.send('flash sale initialized! Stock: 100');
});
// 2. The "Buy" Endpoint (CONTAINS A CRITICAL BUG)
// The "Note" (Lua Script)
// It says: Check stock. If > 0, decrease it. All in one go.
const buyScript = `
local stock = tonumber(redis.call('get', KEYS[1]))
if stock > 0 then
redis.call('decr', KEYS[1])
return 1
else
return 0
end
`;
app.post('/buy',async (req,res)=>{
try {
const result = await redis.eval(buyScript,1,'iphone_stock');
if(result === 1){
const orderData = {
userId: 'user_' + Math.floor(Math.random() * 1000), // Random user
item: 'iPhone 15',
price: 1000,
quantity: 1,
timeStamp: new Date()
};
// Send the message to the 'orders' queue
channel.sendToQueue('orders', Buffer.from(JSON.stringify(orderData)));
console.log('🎉 Sent to Queue:', orderData.userId);
res.json({ message: 'Order Placed! Confirmation sent.' });
} else {
console.log('Sold Out!');
res.status(400).json({ message: 'Sold Out!' });
}
} catch (error) {
console.error(err);
res.status(500).send('Server Error');
}
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));