-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100-seat.js
99 lines (73 loc) · 2.33 KB
/
100-seat.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
97
98
99
import express from 'express';
import kue from 'kue';
import redis from 'redis';
import { promisify } from 'util';
// utils =================================================
// redis =================================================
const client = redis.createClient();
const getAsync = promisify(client.get).bind(client);
let reservationEnabled;
const seatsKey = 'available_seats';
function reserveSeat(number) {
client.set(seatsKey, number);
}
async function getCurrentAvailableSeats() {
const availableSeats = await getAsync(seatsKey);
return availableSeats;
}
client.on('error', (error) => {
console.log(`Redis client not connected to the server: ${error.message}`);
});
client.on('connect', () => {
console.log('Redis client connected to the server');
reserveSeat(50);
reservationEnabled = true;
});
// kue =================================================
const queue = kue.createQueue();
const queueName = 'reserve_seat';
// express =================================================
const app = express();
const port = 1245;
app.listen(port, () => {
console.log(`app listening at http://localhost:${port}`);
});
app.get('/available_seats', async (req, res) => {
const availableSeats = await getCurrentAvailableSeats();
res.json({ numberOfAvailableSeats: availableSeats });
});
app.get('/reserve_seat', (req, res) => {
if (reservationEnabled === false) {
res.json({ status: 'Reservation are blocked' });
return;
}
const jobFormat = {};
const job = queue.create(queueName, jobFormat).save((err) => {
if (err) {
res.json({ status: 'Reservation failed' });
} else {
res.json({ status: 'Reservation in process' });
}
});
job.on('complete', () => {
console.log(`Seat reservation job ${job.id} completed`);
});
job.on('failed', (errorMessage) => {
console.log(`Seat reservation job ${job.id} failed: ${errorMessage}`);
});
});
app.get('/process', async (req, res) => {
queue.process(queueName, async (job, done) => {
let availableSeats = await getCurrentAvailableSeats();
if (availableSeats <= 0) {
done(Error('Not enough seats available'));
}
availableSeats = Number(availableSeats) - 1;
reserveSeat(availableSeats);
if (availableSeats <= 0) {
reservationEnabled = false;
}
done();
});
res.json({ status: 'Queue processing' });
});