Skip to content

Commit

Permalink
fix(generate assignment): changed api route
Browse files Browse the repository at this point in the history
  • Loading branch information
then00bprogrammer committed May 2, 2024
1 parent f348609 commit cf60373
Showing 1 changed file with 31 additions and 21 deletions.
52 changes: 31 additions & 21 deletions client/src/pages/api/subscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,44 @@ import Redis from 'ioredis';
export default async function handler(req:any, res:any) {
if (req.method === 'GET') {
const { id } = req.query;
const key=`generate_assignment_id_${id}`
const key = `generate_assignment_id_${id}`;

const redis = new Redis(process.env.NEXT_PUBLIC_REDIS_URL as string);

redis.subscribe(key, (err, count) => {
if (err) {
console.error('Error subscribing to channel', err);
return res.status(500).json({ error: 'Error subscribing to channel' });
}
console.log(`Subscribed to ${count} channel.`);
});
const subscriptionPromise = new Promise((resolve, reject) => {
redis.subscribe(key, (err, count) => {
if (err) {
console.error('Error subscribing to channel', err);
reject(err);
}
console.log(`Subscribed to ${count} channel.`);
});

redis.on('message', (channel, message) => {
console.log(`Received message ${message} from channel ${channel}`);

const parsedMessage = JSON.parse(message);
if (parsedMessage.id === id) {
console.log('Received message with desired ID:', parsedMessage);
res.status(200).json(parsedMessage); // Send response here
redis.on('message', (channel, message) => {
console.log(`Received message ${message} from channel ${channel}`);

const parsedMessage = JSON.parse(message);
if (parsedMessage.id === id) {
console.log('Received message with desired ID:', parsedMessage);
resolve(parsedMessage);
redis.unsubscribe();
redis.quit();
}
});

req.on('close', () => {
redis.unsubscribe();
redis.quit();
}
reject(new Error('Request closed'));
});
});

req.on('close', () => {
redis.unsubscribe();
redis.quit();
});
try {
const data = await subscriptionPromise;
res.status(200).json(data);
} catch (error) {
res.status(500).json({ error: "Assignment not generated" });
}
} else {
res.setHeader('Allow', ['GET']);
res.status(405).end(`Method ${req.method} Not Allowed`);
Expand Down

0 comments on commit cf60373

Please sign in to comment.