|
| 1 | +import { Request, Response } from 'express'; |
| 2 | + |
| 3 | +import { client as redisClient } from '../lib/db'; |
| 4 | + |
| 5 | +export const cancelMatchRequestController = async (req: Request, res: Response) => { |
| 6 | + const { userId } = req.body; // Only check for userId |
| 7 | + |
| 8 | + if (!userId) { |
| 9 | + return res.status(400).json({ message: 'User ID is required' }); // No need for roomId |
| 10 | + } |
| 11 | + |
| 12 | + try { |
| 13 | + if (!redisClient.isOpen) { |
| 14 | + await redisClient.connect(); |
| 15 | + } |
| 16 | + |
| 17 | + // Check pending status using only userId |
| 18 | + const exists = await redisClient.exists(`match:${userId}`); |
| 19 | + |
| 20 | + if (exists) { |
| 21 | + console.log(`Redis key for user ${userId} exists.`); |
| 22 | + } else { |
| 23 | + console.error(`Redis key for user ${userId} does NOT exist!`); |
| 24 | + } |
| 25 | + |
| 26 | + const pendingStatus = await redisClient.hGet(`match:${userId}`, 'pending'); |
| 27 | + console.log(pendingStatus); |
| 28 | + const data = await redisClient.hGetAll(`match:${userId}`); |
| 29 | + console.log(`Data stored in Redis for user ${userId}:`, data); |
| 30 | + |
| 31 | + if (pendingStatus === 'true') { |
| 32 | + // Allow cancellation and remove from queue based on userId |
| 33 | + await redisClient.del(`match:${userId}`); |
| 34 | + console.log(`User ${userId} has canceled their match.`); |
| 35 | + return res.status(200).json({ message: 'Match canceled successfully' }); |
| 36 | + } else { |
| 37 | + // If the match is no longer pending, deny cancellation |
| 38 | + console.log(`User ${userId} is no longer pending and cannot cancel.`); |
| 39 | + return res |
| 40 | + .status(403) |
| 41 | + .json({ message: 'Match cancellation failed: Request is not pending.' }); |
| 42 | + } |
| 43 | + } catch (error) { |
| 44 | + console.error('Error canceling match:', error); |
| 45 | + return res.status(500).json({ message: 'Server error, please try again later' }); |
| 46 | + } |
| 47 | +}; |
0 commit comments