fix: Replace the bunch of db functions with a Db class

This commit is contained in:
April Hall 2025-02-05 18:31:23 -05:00
parent fd8b8cdfd3
commit 95108ab9eb
Signed by: arithefirst
GPG Key ID: 4508A15C4DB91C5B
4 changed files with 66 additions and 52 deletions

View File

@ -1,54 +1,66 @@
import cassandra from 'cassandra-driver'; import cassandra from 'cassandra-driver';
async function createChannel(client: cassandra.Client, channelName: string) { class Db {
try { private client: cassandra.Client;
await client.execute(`
CREATE TABLE IF NOT EXISTS channels.channel_${channelName} (
id UUID,
message_content TEXT,
channel_name TEXT,
timestamp TIMESTAMP,
sender UUID,
PRIMARY KEY (channel_name, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC);`);
} catch (e) {
// @ts-expect-error I don't like this thing yelling at me
console.log(`Error creating new channel: ${e.message}`);
}
}
async function storeMessage(client: cassandra.Client, channelName: string, content: string, sender: string, id: string) { constructor(client: cassandra.Client) {
try { this.client = client;
const now = new Date();
await client.execute(`INSERT INTO channels.channel_${channelName} (id, message_content, channel_name, timestamp, sender)
VALUES (${id}, '${content}', '${channelName}', ${now.getTime()}, ${sender})`);
} catch (e) {
// @ts-expect-error I don't like this thing yelling at me
console.log(`Error storing messages: ${e.message}`);
} }
}
async function getChannels(client: cassandra.Client): Promise<cassandra.types.Row[] | undefined> { // Create Channel Method
try { async createChannel(channelName: string) {
const res = await client.execute(`SELECT table_name FROM system_schema.tables WHERE keyspace_name = 'channels'`); try {
return res.rows; await this.client.execute(`
} catch (e) { CREATE TABLE IF NOT EXISTS channels.channel_${channelName} (
// @ts-expect-error I don't like this thing yelling at me id UUID,
console.log(`Error fetching channels: ${e.message}`); message_content TEXT,
return; channel_name TEXT,
timestamp TIMESTAMP,
sender UUID,
PRIMARY KEY (channel_name, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC);`);
} catch (e) {
// @ts-expect-error I don't like this thing yelling at me
console.log(`Error creating new channel: ${e.message}`);
}
} }
}
async function getMessages(client: cassandra.Client, channelName: string, limit: number): Promise<cassandra.types.Row[] | undefined> { // Send message method
try { async sendMessage(channelName: string, content: string, sender: string, id: string) {
const res = await client.execute( try {
`SELECT * FROM channels.channel_${channelName} WHERE channel_name = '${channelName}' ORDER BY timestamp DESC LIMIT ${limit}`, const now = new Date();
); await this.client.execute(`INSERT INTO channels.channel_${channelName} (id, message_content, channel_name, timestamp, sender)
return res.rows; VALUES (${id}, '${content}', '${channelName}', ${now.getTime()}, ${sender})`);
} catch (e) { } catch (e) {
// @ts-expect-error I don't like this thing yelling at me // @ts-expect-error I don't like this thing yelling at me
console.log(`Error fetching messages: ${e.message}`); console.log(`Error storing messages: ${e.message}`);
return; }
}
// Get Channels method
async getChannels(): Promise<cassandra.types.Row[] | undefined> {
try {
const res = await this.client.execute(`SELECT table_name FROM system_schema.tables WHERE keyspace_name = 'channels'`);
return res.rows;
} catch (e) {
// @ts-expect-error I don't like this thing yelling at me
console.log(`Error fetching channels: ${e.message}`);
return;
}
}
// Get messages method
async getMessages(channelName: string, limit: number): Promise<cassandra.types.Row[] | undefined> {
try {
const res = await this.client.execute(
`SELECT * FROM channels.channel_${channelName} WHERE channel_name = '${channelName}' ORDER BY timestamp DESC LIMIT ${limit}`,
);
return res.rows;
} catch (e) {
// @ts-expect-error I don't like this thing yelling at me
console.log(`Error fetching messages: ${e.message}`);
return;
}
} }
} }
@ -76,4 +88,6 @@ try {
process.exit(1); process.exit(1);
} }
export { client, createChannel, getChannels, getMessages, storeMessage }; const db = new Db(client);
export { db };

View File

@ -2,7 +2,7 @@ import { Server as SocketIOServer } from 'socket.io';
import type { HttpServer } from 'vite'; import type { HttpServer } from 'vite';
// Don't try to replace with $lib alias. Since this // Don't try to replace with $lib alias. Since this
// file gets loaded as a vite plugin, it will crash // file gets loaded as a vite plugin, it will crash
import { client, createChannel, storeMessage } from './server/db/'; import { db } from './server/db/';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
let io: SocketIOServer | undefined; let io: SocketIOServer | undefined;
@ -21,8 +21,8 @@ export function startupSocketIOServer(httpServer: HttpServer | null) {
if (msg.content !== '') { if (msg.content !== '') {
console.log(`[ws:kit] message from ${socket.id}: ${msg.content}`); console.log(`[ws:kit] message from ${socket.id}: ${msg.content}`);
// Store the message in the database // Store the message in the database
await createChannel(client, '000'); await db.createChannel('000');
await storeMessage(client, '000', msg.content, msg.id, uuidv4()); await db.sendMessage('000', msg.content, msg.id, uuidv4());
io!.emit('message', { io!.emit('message', {
user: msg.id, user: msg.id,
message: msg.content, message: msg.content,

View File

@ -1,8 +1,8 @@
import { getChannels, client } from '$lib/server/db'; import { db } from '$lib/server/db';
import type { LayoutServerLoad } from './$types'; import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async () => { export const load: LayoutServerLoad = async () => {
const rows = await getChannels(client); const rows = await db.getChannels();
const channels: string[] = rows const channels: string[] = rows
? rows.map((value) => { ? rows.map((value) => {
return value.table_name; return value.table_name;

View File

@ -1,8 +1,8 @@
import type { TypeMessage } from '$lib'; import type { TypeMessage } from '$lib';
import { getMessages, client } from '$lib/server/db'; import { db } from '$lib/server/db';
export async function load(): Promise<{ messages: TypeMessage[] }> { export async function load(): Promise<{ messages: TypeMessage[] }> {
const rows = await getMessages(client, '000', 50); const rows = await db.getMessages('000', 50);
const messages: TypeMessage[] = rows const messages: TypeMessage[] = rows
? rows.map((value) => { ? rows.map((value) => {
return { return {