I’m using node.js and socket.io v4.8.0. I’m trying to create a basic chat application that updates my postgress db once an event such as “send message” has been called. I am able to establish a connection. However whenever I try to listen to an event the callback function is never triggered.
My client side and server side version match too both being v4+
import express from "express";
import { Server } from "socket.io";
import { authMiddleware } from "./middleware";
import { createServer } from "http";
import { getDb } from "./db";
import { chatParticipant, message } from "./schema";
import { and, eq } from "drizzle-orm";
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer);
const port = process.env.PORT || 8080;
const db = getDb();
app.use(authMiddleware);
app.use(express.json());
const INACTIVITY_TIMEOUT = 10 * 60 * 1000;
io.on("connection", (socket) => {
console.log("A user connected");
let currentChatId: number | null = null;
let currentUserId: string | null = null;
let inactivityTimer: NodeJS.Timeout | null = null;
function resetInactivityTimer() {
if (inactivityTimer) {
clearTimeout(inactivityTimer);
}
inactivityTimer = setTimeout(() => {
console.log(`Closing inactive connection for user ${currentUserId}`);
socket.disconnect(true);
}, INACTIVITY_TIMEOUT);
}
resetInactivityTimer();
socket.on("join chat", async (chatId: number, userId: string) => {
console.log("join chat", chatId, userId);
resetInactivityTimer();
try {
const userChatParticipant = await db.query.chatParticipant.findFirst({
where: and(
eq(chatParticipant.chatId, chatId),
eq(chatParticipant.userId, userId)
),
});
if (!userChatParticipant) {
socket.emit("error", "You are not a participant of this chat");
return;
}
currentChatId = chatId;
currentUserId = userId;
socket.join(`chat_${chatId}`);
console.log(`User ${userId} joined chat ${chatId}`);
const recentMessages = await db
.select()
.from(message)
.where(eq(message.chatId, chatId))
.orderBy(message.createdAt)
.limit(50);
socket.emit("recent messages", recentMessages);
} catch (error) {
console.error("Error joining chat:", error);
socket.emit("error", "An error occurred while joining the chat");
}
});
socket.on("leave chat", () => {
resetInactivityTimer();
if (currentChatId && currentUserId) {
socket.leave(`chat_${currentChatId}`);
console.log(`User ${currentUserId} left chat ${currentChatId}`);
currentChatId = null;
currentUserId = null;
}
});
socket.on("send message", async (content: string) => {
resetInactivityTimer();
if (!currentChatId || !currentUserId) {
socket.emit("error", "You are not in a chat room");
return;
}
try {
const [newMessage] = await db
.insert(message)
.values({
senderId: currentUserId,
chatId: currentChatId,
content,
})
.returning();
io.to(`chat_${currentChatId}`).emit("new message", {
...newMessage,
content: newMessage.content,
});
} catch (error) {
console.error("Error sending message:", error);
socket.emit("error", "An error occurred while sending the message");
}
});
socket.on("disconnect", () => {
console.log("User disconnected");
if (inactivityTimer) {
clearTimeout(inactivityTimer);
}
});
});
// Start the server
httpServer.listen(port, () => {
console.log(`Server is running on port ${port}`);
});```
Expecting the console logs to be logged and the database to be updated/queried.