websocket message types changed
This commit is contained in:
parent
00332b4648
commit
376ffa651a
|
|
@ -3,8 +3,6 @@ import { useLotteryAuth } from "@/store/useLotteryAuth";
|
|||
import { LotteryWinnerDataSimplified } from "@/typings/lottery/lottery.types";
|
||||
import LotteryWinnersList from "./winners/LotteryWinnersList";
|
||||
import LotterySlotCounter from "./slotCounter/LotterySlotCounter";
|
||||
import ReactConfetti from "react-confetti";
|
||||
import { useWindowSize } from "react-use";
|
||||
import AnimatedText from "@/components/common/AnimatedText";
|
||||
import { useWebsocketLottery } from "@/hooks/useWebSocketLottery";
|
||||
import Confetti from "../common/Confetti";
|
||||
|
|
@ -40,11 +38,11 @@ const LotteryWinnersSection = ({
|
|||
`${WEBSOCKET_URL}${lotteryData?.data.sms_number}`
|
||||
);
|
||||
|
||||
// Simulate WebSocket messages for testing
|
||||
// Simulate WebSocket message for testing
|
||||
const simulateMessage = () => {
|
||||
const dummyWinner: LotteryWinnerDataSimplified = {
|
||||
client: `9936${Math.floor(10000000 + Math.random() * 90000000)}`,
|
||||
winner_no: winners.length + 1,
|
||||
phone: `9936${Math.floor(10000000 + Math.random() * 90000000)}`, // Generate random client number
|
||||
winner_no: winners.length + 1, // Increment winner number
|
||||
ticket: `${Math.floor(Math.random() * 99)
|
||||
.toString()
|
||||
.padStart(2, "0")}-${Math.floor(Math.random() * 99)
|
||||
|
|
@ -55,17 +53,28 @@ const LotteryWinnersSection = ({
|
|||
.toString()
|
||||
.padStart(2, "0")}-${Math.floor(Math.random() * 99)
|
||||
.toString()
|
||||
.padStart(2, "0")}`,
|
||||
.padStart(2, "0")}`, // Generate random ticket
|
||||
};
|
||||
|
||||
console.log("📩 Simulated Message:", dummyWinner); // Log the simulated message
|
||||
setMessageQueue((prevQueue) => [...prevQueue, dummyWinner]);
|
||||
};
|
||||
|
||||
// useEffect(() => {
|
||||
// const interval = setInterval(() => {
|
||||
// simulateMessage();
|
||||
// }, 20000); // Trigger every 10 seconds
|
||||
|
||||
// return () => clearInterval(interval); // Clean up interval on unmount
|
||||
// }, []);
|
||||
|
||||
// Initialize winners from lottery data
|
||||
useEffect(() => {
|
||||
console.log("🎟️ Lottery Data:", lotteryData);
|
||||
|
||||
if (lotteryData && lotteryData.data.winners.length > 0) {
|
||||
const simplifiedWinners = lotteryData.data.winners.map((winner) => ({
|
||||
client: winner.client,
|
||||
phone: winner.client,
|
||||
winner_no: winner.winner_no,
|
||||
ticket: winner.ticket,
|
||||
}));
|
||||
|
|
@ -74,7 +83,7 @@ const LotteryWinnersSection = ({
|
|||
const lastWinner = simplifiedWinners[simplifiedWinners.length - 1];
|
||||
setWinnerSelectingStatus("selected");
|
||||
setTopText(`${lastWinner.winner_no}-nji ýeňiji`);
|
||||
setBottomText(lastWinner.client);
|
||||
setBottomText(lastWinner.phone);
|
||||
setIsConfettiActive(true);
|
||||
}
|
||||
}, [lotteryData]);
|
||||
|
|
@ -84,9 +93,13 @@ const LotteryWinnersSection = ({
|
|||
const unsubscribe = subscribeToMessages((event) => {
|
||||
try {
|
||||
const newWinner: LotteryWinnerDataSimplified = JSON.parse(event.data);
|
||||
console.log("📩 WebSocket Message Received:", newWinner); // Log the parsed message
|
||||
|
||||
// Add new message to the queue
|
||||
setMessageQueue((prevQueue) => [...prevQueue, newWinner]);
|
||||
setMessageQueue((prevQueue) => {
|
||||
console.log("📥 Adding to Queue:", newWinner);
|
||||
return [...prevQueue, newWinner];
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error parsing WebSocket message:", error);
|
||||
}
|
||||
|
|
@ -97,6 +110,8 @@ const LotteryWinnersSection = ({
|
|||
|
||||
// Process queue when a new message is added
|
||||
useEffect(() => {
|
||||
console.log("📋 Current Message Queue:", messageQueue);
|
||||
|
||||
if (!isProcessing && messageQueue.length > 0) {
|
||||
processQueue();
|
||||
}
|
||||
|
|
@ -109,6 +124,8 @@ const LotteryWinnersSection = ({
|
|||
setIsProcessing(true); // Lock processing
|
||||
const message = messageQueue[0]; // Get the first message in the queue
|
||||
|
||||
console.log("⚙️ Processing Message:", message); // Debug Log 4: Log the message being processed
|
||||
|
||||
try {
|
||||
await handleMessage(message); // Process the message
|
||||
} catch (error) {
|
||||
|
|
@ -121,6 +138,7 @@ const LotteryWinnersSection = ({
|
|||
|
||||
// Handle the logic for processing a single WebSocket message
|
||||
const handleMessage = async (winner: LotteryWinnerDataSimplified) => {
|
||||
console.log("⬇️ Updating Top and Bottom Text:", winner); // Debug Log 5: Log winner data before setting states
|
||||
setIsConfettiActive(false);
|
||||
setTopText(`${winner.winner_no}-nji ýeňiji saýlanýar`);
|
||||
setBottomText("...");
|
||||
|
|
@ -133,7 +151,9 @@ const LotteryWinnersSection = ({
|
|||
|
||||
// Finalize winner selection
|
||||
setTopText(`${winner.winner_no}-nji ýeňiji`);
|
||||
setBottomText(winner.client);
|
||||
setBottomText(winner.phone);
|
||||
console.log("⬇️ Finalized Bottom Text:", winner.phone); // Debug Log 6: Log the final bottomText update
|
||||
|
||||
setWinnerSelectingStatus("selected");
|
||||
setIsConfettiActive(true);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,16 @@
|
|||
import { LotteryWinnerData, LotteryWinnerDataSimplified } from '@/typings/lottery/lottery.types';
|
||||
import LotteryWinner from './LotteryWinner';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { v4 } from 'uuid';
|
||||
import {
|
||||
LotteryWinnerData,
|
||||
LotteryWinnerDataSimplified,
|
||||
} from "@/typings/lottery/lottery.types";
|
||||
import LotteryWinner from "./LotteryWinner";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { v4 } from "uuid";
|
||||
|
||||
const LotteryWinnersList = ({ winners }: { winners: LotteryWinnerDataSimplified[] }) => {
|
||||
const LotteryWinnersList = ({
|
||||
winners,
|
||||
}: {
|
||||
winners: LotteryWinnerDataSimplified[];
|
||||
}) => {
|
||||
return (
|
||||
<div className="flex flex-col gap-4 w-full max-w-[1028px]">
|
||||
<div className="flex flex-col gap-2 w-full pb-4 border-b border-[#CECCFF]">
|
||||
|
|
@ -11,11 +18,12 @@ const LotteryWinnersList = ({ winners }: { winners: LotteryWinnerDataSimplified[
|
|||
</div>
|
||||
<motion.div
|
||||
layout
|
||||
className="grid min-[1025px]:grid-cols-3 min-[700px]:grid-cols-2 grid-cols-1 gap-x-2 gap-y-4 w-full lottery-winner-list">
|
||||
className="grid min-[1025px]:grid-cols-3 min-[700px]:grid-cols-2 grid-cols-1 gap-x-2 gap-y-4 w-full lottery-winner-list"
|
||||
>
|
||||
{winners.map((item, index) => (
|
||||
<LotteryWinner
|
||||
key={v4()}
|
||||
phone={item.client}
|
||||
phone={item.phone}
|
||||
ticket={item.ticket}
|
||||
winnerNumber={item.winner_no}
|
||||
isNew={index === winners.length - 1}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useState, useEffect, useRef } from "react";
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
|
||||
export const useWebsocketLottery = (url: string) => {
|
||||
const [wsStatus, setWsStatus] = useState<
|
||||
|
|
@ -14,15 +14,15 @@ export const useWebsocketLottery = (url: string) => {
|
|||
const setupWebSocket = () => {
|
||||
if (!isMounted) return;
|
||||
|
||||
console.log("🔄 Connecting to WebSocket...");
|
||||
console.log("🔄 [WebSocket] Connecting...");
|
||||
const socket = new WebSocket(url);
|
||||
wsRef.current = socket;
|
||||
|
||||
socket.onopen = () => {
|
||||
if (!isMounted) return;
|
||||
|
||||
console.log("✅ WebSocket connected");
|
||||
console.log("WebSocket url", url);
|
||||
console.log("✅ [WebSocket] Connected");
|
||||
console.log("🔗 [WebSocket URL]:", url);
|
||||
setWsStatus("connected");
|
||||
if (reconnectTimeoutRef.current)
|
||||
clearTimeout(reconnectTimeoutRef.current);
|
||||
|
|
@ -31,21 +31,21 @@ export const useWebsocketLottery = (url: string) => {
|
|||
socket.onmessage = (event) => {
|
||||
if (!isMounted) return;
|
||||
|
||||
console.log("📩 Message received:", event.data);
|
||||
console.log("📩 [WebSocket] Message received:", event.data);
|
||||
messageListeners.current.forEach((listener) => listener(event));
|
||||
};
|
||||
|
||||
socket.onerror = () => {
|
||||
if (!isMounted) return;
|
||||
|
||||
console.error("❌ WebSocket error");
|
||||
console.error("❌ [WebSocket] Error occurred");
|
||||
setWsStatus("error");
|
||||
};
|
||||
|
||||
socket.onclose = () => {
|
||||
if (!isMounted) return;
|
||||
|
||||
console.log("❌ WebSocket closed");
|
||||
console.log("❌ [WebSocket] Closed");
|
||||
setWsStatus("closed");
|
||||
reconnectWebSocket();
|
||||
};
|
||||
|
|
@ -54,7 +54,7 @@ export const useWebsocketLottery = (url: string) => {
|
|||
const reconnectWebSocket = () => {
|
||||
if (!isMounted) return;
|
||||
|
||||
console.log("🔄 Reconnecting to WebSocket...");
|
||||
console.log("🔄 [WebSocket] Reconnecting in 5 seconds...");
|
||||
reconnectTimeoutRef.current = setTimeout(() => {
|
||||
setupWebSocket();
|
||||
}, 5000);
|
||||
|
|
@ -63,7 +63,7 @@ export const useWebsocketLottery = (url: string) => {
|
|||
setupWebSocket();
|
||||
|
||||
return () => {
|
||||
console.log("🔌 Cleaning up WebSocket connection...");
|
||||
console.log("🔌 [WebSocket] Cleaning up...");
|
||||
isMounted = false;
|
||||
|
||||
if (wsRef.current) {
|
||||
|
|
@ -77,21 +77,26 @@ export const useWebsocketLottery = (url: string) => {
|
|||
};
|
||||
}, [url]);
|
||||
|
||||
const sendPing = () => {
|
||||
const sendPing = useCallback(() => {
|
||||
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
||||
console.log("📤 Sending ping");
|
||||
console.log("📤 [WebSocket] Sending ping");
|
||||
wsRef.current.send(JSON.stringify({ type: "ping" }));
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const subscribeToMessages = (listener: (event: MessageEvent) => void) => {
|
||||
const subscribeToMessages = useCallback(
|
||||
(listener: (event: MessageEvent) => void) => {
|
||||
console.log("👂 [WebSocket] Subscribing to messages");
|
||||
messageListeners.current.push(listener);
|
||||
return () => {
|
||||
console.log("❌ [WebSocket] Unsubscribing from messages");
|
||||
messageListeners.current = messageListeners.current.filter(
|
||||
(l) => l !== listener
|
||||
);
|
||||
};
|
||||
};
|
||||
},
|
||||
[] // Empty array ensures it's memoized
|
||||
);
|
||||
|
||||
return { wsStatus, sendPing, subscribeToMessages };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -23,9 +23,9 @@ export interface LotteryResponse {
|
|||
}
|
||||
|
||||
export interface LotteryWinnerDataSimplified {
|
||||
client: string;
|
||||
phone: string;
|
||||
winner_no: number;
|
||||
ticket: string;
|
||||
}
|
||||
|
||||
export type LotteryStatus = 'not-started' | 'started' | 'ended';
|
||||
export type LotteryStatus = "not-started" | "started" | "ended";
|
||||
|
|
|
|||
Loading…
Reference in New Issue