diff --git a/bun.lockb b/bun.lockb index 81cb291..b4d6c32 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/package.json b/package.json index bba1ead..fd4f8d2 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "express": "^4.21.2", "socket.io": "^4.8.1", "socket.io-client": "^4.8.1", - "tsm": "^2.3.0" + "tsm": "^2.3.0", + "uuid": "^11.0.4" } } diff --git a/src/lib/server/db/index.ts b/src/lib/server/db/index.ts index 994d0a4..a355a15 100644 --- a/src/lib/server/db/index.ts +++ b/src/lib/server/db/index.ts @@ -1,5 +1,26 @@ import cassandra from 'cassandra-driver'; +async function createChannel(client: cassandra.Client, channelName: string) { + await client.execute(` + CREATE TABLE IF NOT EXISTS channels.channel_${channelName} ( + id UUID PRIMARY KEY, + message_content TEXT, + timestamp TIMESTAMP, + sender UUID + );`) +} + +async function storeMessage( + client: cassandra.Client, + channelName: string, + content: string, + sender: string, + id: string) { + const now = new Date(); + await client.execute(`INSERT INTO channels.channel_${channelName} (id, message_content, timestamp, sender) + VALUES (${id}, '${content}', ${now.getTime()}, ${sender})`) +} + const client = new cassandra.Client({ contactPoints: ['localhost'], localDataCenter: 'datacenter1', @@ -11,4 +32,4 @@ await client.connect(); await client.execute(`CREATE KEYSPACE IF NOT EXISTS users WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1};`); await client.execute(`CREATE KEYSPACE IF NOT EXISTS channels WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1};`); -export default client; +export { client, createChannel, storeMessage }; \ No newline at end of file diff --git a/src/lib/websocketConfig.ts b/src/lib/websocketConfig.ts index b914f51..cb3895c 100644 --- a/src/lib/websocketConfig.ts +++ b/src/lib/websocketConfig.ts @@ -1,6 +1,7 @@ import { Server as SocketIOServer } from 'socket.io'; import type { HttpServer } from 'vite'; -import client from './server/db/'; +import { client, createChannel, storeMessage } from './server/db/'; +import { v4 as uuidv4 } from 'uuid'; let io: SocketIOServer | undefined; @@ -9,13 +10,15 @@ export function startupSocketIOServer(httpServer: HttpServer | null) { console.log('[ws:kit] setup'); io = new SocketIOServer(httpServer); - io.on('connection', (socket) => { + io.on('connection', async (socket) => { // Runs on client connect console.log(`[ws:kit] client connected (${socket.id})`); - // Runs on message receive - socket.on('message', (msg) => { + socket.on('message', async (msg) => { console.log(`[ws:kit] message from ${socket.id}: ${msg}`); + // Store the message in the database + await createChannel(client, '000'); + await storeMessage(client, '000', msg, uuidv4(), uuidv4()); io!.emit('message', { user: socket.id, message: msg,