|
| 1 | +import type { Request, Response } from 'express'; |
| 2 | +import { StatusCodes } from 'http-status-codes'; |
| 3 | + |
| 4 | +import { client as redisClient, logQueueStatus } from '@/lib/db'; |
| 5 | +import { STREAM_NAME } from '@/lib/db/constants'; |
| 6 | +import { getPoolKey, getStreamId, logger } from '@/lib/utils'; |
| 7 | +import { io } from '@/server'; |
| 8 | +import { MATCHING_EVENT } from '@/ws/events'; |
| 9 | + |
| 10 | +export const cancelMatchRequestController = async (req: Request, res: Response) => { |
| 11 | + const { userId } = req.body; // Only check for userId |
| 12 | + |
| 13 | + if (!userId) { |
| 14 | + return res.status(StatusCodes.UNPROCESSABLE_ENTITY).json({ message: 'User ID is required' }); // No need for roomId |
| 15 | + } |
| 16 | + |
| 17 | + try { |
| 18 | + if (!redisClient.isOpen) { |
| 19 | + await redisClient.connect(); |
| 20 | + } |
| 21 | + |
| 22 | + // Check pending status using only userId |
| 23 | + const result = await redisClient |
| 24 | + .hGetAll(getPoolKey(userId)) |
| 25 | + .then(async (value) => { |
| 26 | + if (value.pending === 'true') { |
| 27 | + const timestamp = value.timestamp; |
| 28 | + await Promise.all([ |
| 29 | + redisClient.del(getPoolKey(userId)), |
| 30 | + timestamp |
| 31 | + ? redisClient.xDel(STREAM_NAME, getStreamId(value.timestamp)) |
| 32 | + : Promise.resolve(), |
| 33 | + ]); |
| 34 | + await logQueueStatus( |
| 35 | + logger, |
| 36 | + redisClient, |
| 37 | + 'Queue Status after cancelling request: <PLACEHOLDER>' |
| 38 | + ); |
| 39 | + logger.info(`Request cancellation successful`); |
| 40 | + const room = value.socketPort; |
| 41 | + |
| 42 | + if (room) { |
| 43 | + io.sockets.in(room).socketsLeave(room); |
| 44 | + } |
| 45 | + |
| 46 | + return { |
| 47 | + success: true, |
| 48 | + }; |
| 49 | + } |
| 50 | + |
| 51 | + return { |
| 52 | + success: false, |
| 53 | + error: `Match in ${MATCHING_EVENT.MATCHING} state.`, |
| 54 | + }; |
| 55 | + }) |
| 56 | + .catch((reason) => { |
| 57 | + if (reason) { |
| 58 | + return { |
| 59 | + success: false, |
| 60 | + error: reason, |
| 61 | + }; |
| 62 | + } |
| 63 | + }); |
| 64 | + |
| 65 | + if (result?.success) { |
| 66 | + return res.status(StatusCodes.OK).end(); |
| 67 | + } else if (!result?.success) { |
| 68 | + return res.status(StatusCodes.FORBIDDEN).json(result?.error); |
| 69 | + } |
| 70 | + } catch (error) { |
| 71 | + console.error('Error canceling match:', error); |
| 72 | + return res.status(500).json({ message: 'Server error, please try again later' }); |
| 73 | + } |
| 74 | +}; |
0 commit comments