Skip to content

Commit 4aa424b

Browse files
committed
Fetch categories from DB
1 parent 6434439 commit 4aa424b

File tree

2 files changed

+41
-21
lines changed

2 files changed

+41
-21
lines changed

Backend/MatchingService/rabbitmq/setup.js

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,24 @@ const matching_exchange_name = "matching_exchange";
55
const dead_letter_exchange_name = "dead_letter_exchange";
66
const dead_letter_queue_name = "dead_letter_queue";
77
const cancel_queue_name = "cancel_queue";
8-
const difficulties = ["easy", "medium", "hard", "any"]; // Add "any" for fallback
9-
const categories = ["data-structures", "strings", "arrays"]; // Adjust to include categories
10-
11-
const queueNames = generator.generateQueueNames(
12-
generator.generateCombinations(difficulties, categories)
13-
);
8+
const difficulties = ["easy", "medium", "hard", "any"];
9+
const axios = require('axios');
10+
const categoryAPIUrl = 'http://localhost:3001/api/categories';
11+
12+
let queueNamesPromise = axios.get(categoryAPIUrl)
13+
.then(response => {
14+
const categories = response.data.map(category => category.name.toLowerCase().replace(/\s+/g, '-'));
15+
console.log("categories from api: ", categories)
16+
return generator.generateQueueNames(generator.generateCombinations(difficulties, categories));
17+
})
18+
.catch(error => {
19+
console.error("Error fetching categories:", error);
20+
return []; // Return an empty array if categories couldn't be fetched
21+
});
1422

1523
async function setupRabbitMQ() {
1624
try {
25+
const queueNames = await queueNamesPromise;
1726
const connection = await amqp.connect(process.env.RABBITMQ_URL);
1827

1928
if (!connection) {
@@ -30,29 +39,27 @@ async function setupRabbitMQ() {
3039

3140
// Declare and bind all main queues with TTL and DLQ bindings
3241
for (let queueName of queueNames) {
33-
await channel.deleteQueue(queueName); // Ensure we start fresh for each setup
42+
await channel.deleteQueue(queueName); // Ensure we start fresh for each setup
3443

3544
await channel.assertQueue(queueName, {
3645
durable: true,
3746
arguments: {
38-
'x-message-ttl': 10000, // 60 seconds TTL
39-
'x-dead-letter-exchange': dead_letter_exchange_name // Bind to dead-letter exchange
47+
'x-message-ttl': 10000, // TTL for messages in the queue
48+
'x-dead-letter-exchange': dead_letter_exchange_name // Bind to dead-letter exchange
4049
}
4150
});
4251

4352
await channel.bindQueue(queueName, matching_exchange_name, queueName); // Bind to exchange
4453
}
4554

46-
// Delete DLQ before asserting it
55+
// Delete and recreate the DLQ
4756
await channel.deleteQueue(dead_letter_queue_name);
48-
49-
// Declare the dead-letter queue and bind it to the dead-letter exchange
5057
await channel.assertQueue(dead_letter_queue_name, { durable: true });
5158
await channel.bindQueue(dead_letter_queue_name, dead_letter_exchange_name, ''); // Bind with no routing key
5259

53-
// Declare and bind the cancel queue
54-
await channel.deleteQueue(cancel_queue_name); // Delete any existing cancel queue
55-
await channel.assertQueue(cancel_queue_name, { durable: true }); // Declare the cancel queue
60+
// Delete and recreate the cancel queue
61+
await channel.deleteQueue(cancel_queue_name);
62+
await channel.assertQueue(cancel_queue_name, { durable: true });
5663
await channel.bindQueue(cancel_queue_name, matching_exchange_name, 'cancel'); // Bind with the "cancel" routing key
5764

5865
console.log("RabbitMQ setup complete with queues, DLQ, and bindings.");
@@ -64,4 +71,4 @@ async function setupRabbitMQ() {
6471
}
6572
}
6673

67-
module.exports = { setupRabbitMQ, matching_exchange_name, queueNames, dead_letter_queue_name , cancel_queue_name};
74+
module.exports = { setupRabbitMQ, matching_exchange_name, queueNamesPromise, dead_letter_queue_name, cancel_queue_name };

Backend/MatchingService/rabbitmq/subscriber.js

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
const amqp = require('amqplib');
2-
const { queueNames } = require('./setup.js');
2+
const { queueNamesPromise } = require('./setup.js');
33
// const { matchUsers } = require('../services/matchingService.js');
44
const { notifyUsers } = require('../websocket/websocket');
55
const { v4: uuidv4 } = require('uuid');
66
// matchingService/fetchQuestion.js
77
const axios = require('axios');
8-
const questionServiceUrl = 'http://localhost:3001/api/questions';
8+
const questionAPIUrl = 'http://localhost:3001/api/questions';
99

1010

1111
// TODO: Subscribe and acknowledge messages with user info when timeout/user matched
@@ -69,7 +69,8 @@ function matchUsers(channel, msg, userId, difficulty, category) {
6969

7070
if (waitingUsers[criteriaKey].length >= 2) {
7171
const matchedUsers = waitingUsers[criteriaKey].splice(0, 2);
72-
delete waitingUsers[categoryKey];
72+
removeMatchedUsersFromOtherLists(matchedUsers, categoryKey);
73+
console.log("waitingusers after strict matching: ", waitingUsers)
7374
notifyMatch(channel, matchedUsers, category);
7475
return true;
7576
}
@@ -80,7 +81,8 @@ function matchUsers(channel, msg, userId, difficulty, category) {
8081
console.log(`Fallback: User ${userId} added to ${categoryKey}. Waiting list: ${waitingUsers[categoryKey].length}`);
8182
if (waitingUsers[categoryKey].length >= 2) {
8283
const matchedUsers = waitingUsers[categoryKey].splice(0, 2);
83-
delete waitingUsers[criteriaKey];
84+
removeMatchedUsersFromOtherLists(matchedUsers, criteriaKey);
85+
console.log("waitingusers after lenient matching: ", waitingUsers)
8486
notifyMatch(channel, matchedUsers, category);
8587
return true;
8688
}
@@ -89,12 +91,22 @@ function matchUsers(channel, msg, userId, difficulty, category) {
8991
return false;
9092
}
9193

94+
function removeMatchedUsersFromOtherLists(matchedUsers, keyToSkip) {
95+
for (const key in waitingUsers) {
96+
if (key !== keyToSkip) {
97+
waitingUsers[key] = waitingUsers[key].filter(
98+
user => !matchedUsers.some(matchedUser => matchedUser.userId === user.userId)
99+
);
100+
}
101+
}
102+
}
103+
92104
async function notifyMatch(channel, matchedUsers, category) {
93105
const roomId = uuidv4();
94106

95107
try {
96108
// Fetch a question from QuestionService based on category
97-
const response = await axios.get(`${questionServiceUrl}/by-category`, {
109+
const response = await axios.get(`${questionAPIUrl}/by-category`, {
98110
params: { category: category }
99111
});
100112

@@ -242,6 +254,7 @@ async function rejectMessage(channel, msg, userId) {
242254

243255
async function consumeQueue() {
244256
try {
257+
const queueNames = await queueNamesPromise;
245258
const connection = await amqp.connect(process.env.RABBITMQ_URL);
246259
const channel = await connection.createChannel();
247260

0 commit comments

Comments
 (0)