From a2a4fdd770cd6d6115c5ce8541f630892fa92b6d Mon Sep 17 00:00:00 2001 From: KevinMidboe Date: Wed, 3 Sep 2025 00:15:47 +0200 Subject: [PATCH] separated db & function code (filament) --- .../{database.ts => database/filament.ts} | 88 +-------------- src/lib/server/database/index.ts | 100 ++++++++++++++++++ src/routes/printer/+page.server.ts | 2 +- src/routes/printer/+page.svelte | 1 + src/routes/printer/filament/+server.ts | 2 +- .../printer/filament/[id]/+page.server.ts | 2 +- 6 files changed, 105 insertions(+), 90 deletions(-) rename src/lib/server/{database.ts => database/filament.ts} (50%) create mode 100644 src/lib/server/database/index.ts diff --git a/src/lib/server/database.ts b/src/lib/server/database/filament.ts similarity index 50% rename from src/lib/server/database.ts rename to src/lib/server/database/filament.ts index f5076c3..67fbe9b 100644 --- a/src/lib/server/database.ts +++ b/src/lib/server/database/filament.ts @@ -1,91 +1,5 @@ -import { currentFilament } from './filament'; -import pg from 'pg'; -import { env } from '$env/dynamic/private'; import type { Filament } from '$lib/interfaces/printer'; - -const { Pool } = pg; - -let pool: InstanceType | undefined; - -async function initDb() { - if (pool) return pool; - - pool = new Pool({ - connectionString: env.DATABASE_URL // e.g. postgres://user:pass@localhost:5432/mydb - }); - - const client = await pool.connect(); - try { - await client.query('BEGIN'); - - for (const stmt of schemas) { - await client.query(stmt); - } - - await client.query('COMMIT'); - } catch (err: any) { - console.error('Failed to create tables:', err.message); - await client.query('ROLLBACK'); - throw err; - } finally { - client.release(); - } - - return pool; -} - -const schemas = [ - ` - CREATE TABLE IF NOT EXISTS filament ( - id SERIAL PRIMARY KEY, - hex TEXT NOT NULL, - color TEXT NOT NULL, - material TEXT, - weight REAL, - link TEXT, - added INTEGER, -- epoch seconds - updated INTEGER, -- epoch seconds - UNIQUE (hex, updated) - ) - ` -]; - -async function seedData(pool: InstanceType) { - const baseTimestamp = Math.floor(new Date('2025-04-01T05:47:01+00:00').getTime() / 1000); - const filaments = currentFilament(); - - const client = await pool.connect(); - try { - await client.query('BEGIN'); - - for (const f of filaments) { - await client.query( - `INSERT INTO filament (hex, color, material, weight, link, added, updated) - VALUES ($1, $2, $3, $4, $5, $6, $7) - ON CONFLICT (hex, updated) DO NOTHING`, - [f.hex, f.color, f.material, f.weight, f.link, baseTimestamp, baseTimestamp] - ); - } - - await client.query('COMMIT'); - } catch (err: any) { - console.error('Failed to seed data:', err.message); - await client.query('ROLLBACK'); - throw err; - } finally { - client.release(); - } -} - -// Export helper to use db elsewhere -async function getDb() { - if (pool) return pool; - - const p = await initDb(); - await seedData(p); - console.log('Database setup and seeding complete!'); - return p; -} +import { getDb } from '../database'; export async function getAllFilament(): Promise> { const pool = await getDb(); diff --git a/src/lib/server/database/index.ts b/src/lib/server/database/index.ts new file mode 100644 index 0000000..ed2feba --- /dev/null +++ b/src/lib/server/database/index.ts @@ -0,0 +1,100 @@ +import pg from 'pg'; +import { env } from '$env/dynamic/private'; +import type { Filament } from '$lib/interfaces/printer'; + +const { Pool } = pg; + +let pool: InstanceType | undefined; + +async function initDb() { + if (pool) return pool; + + pool = new Pool({ + connectionString: env.DATABASE_URL // e.g. postgres://user:pass@localhost:5432/mydb + }); + + const client = await pool.connect(); + try { + await client.query('BEGIN'); + + for (const stmt of schemas) { + await client.query(stmt); + } + + await client.query('COMMIT'); + } catch (err: any) { + console.error('Failed to create tables:', err.message); + await client.query('ROLLBACK'); + throw err; + } finally { + client.release(); + } + + return pool; +} + +const schemas = [ + ` + CREATE TABLE IF NOT EXISTS filament ( + id SERIAL PRIMARY KEY, + hex TEXT NOT NULL, + color TEXT NOT NULL, + material TEXT, + weight REAL, + link TEXT, + added INTEGER, -- epoch seconds + updated INTEGER, -- epoch seconds + UNIQUE (hex, updated) + ) + `, + ` + CREATE TABLE IF NOT EXISTS site ( + id SERIAL PRIMARY KEY, + name TEXT NOT NULL, + color TEXT NOT NULL, + image TEXT, + link TEXT, + background TEXT, + created INTEGER, -- epoch seconds + updated INTEGER, -- epoch seconds + UNIQUE (name, updated) + ) + ` +]; + +async function seedFilament(pool: InstanceType) { + const baseTimestamp = Math.floor(new Date('2025-04-01T05:47:01+00:00').getTime() / 1000); + const filaments: Filament[] = []; // disables seed + + const client = await pool.connect(); + try { + await client.query('BEGIN'); + + for (const f of filaments) { + await client.query( + `INSERT INTO filament (hex, color, material, weight, link, added, updated) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (hex, updated) DO NOTHING`, + [f.hex, f.color, f.material, f.weight, f.link, baseTimestamp, baseTimestamp] + ); + } + + await client.query('COMMIT'); + } catch (err: any) { + console.error('Failed to seed data:', err.message); + await client.query('ROLLBACK'); + throw err; + } finally { + client.release(); + } +} + +// Export helper to use db elsewhere +export async function getDb() { + if (pool) return pool; + + const p = await initDb(); + await seedFilament(p); + console.log('Database setup and seeding complete!'); + return p; +} diff --git a/src/routes/printer/+page.server.ts b/src/routes/printer/+page.server.ts index 90d20d3..09a8aff 100644 --- a/src/routes/printer/+page.server.ts +++ b/src/routes/printer/+page.server.ts @@ -1,6 +1,6 @@ import type { PageServerLoad } from './$types'; import { fetchP1P } from '$lib/server/homeassistant'; -import { getAllFilament } from '$lib/server/database'; +import { getAllFilament } from '$lib/server/database/filament'; import type { Filament } from '$lib/interfaces/printer'; interface PrinterState { diff --git a/src/routes/printer/+page.svelte b/src/routes/printer/+page.svelte index 22a4019..7875783 100644 --- a/src/routes/printer/+page.svelte +++ b/src/routes/printer/+page.svelte @@ -46,6 +46,7 @@ let open = $state(false); let timeLeftInterval: ReturnType; + console.log("got data:", data) const rawFilament: Filament[] = data?.filament || []; let filament = $derived( rawFilament diff --git a/src/routes/printer/filament/+server.ts b/src/routes/printer/filament/+server.ts index 3256e5f..4e38257 100644 --- a/src/routes/printer/filament/+server.ts +++ b/src/routes/printer/filament/+server.ts @@ -1,4 +1,4 @@ -import { addFilament, updateFilament } from '$lib/server/database'; +import { addFilament, updateFilament } from '$lib/server/database/filament'; import { json } from '@sveltejs/kit'; export const PUT: RequestHandler = async ({ params, request }) => { diff --git a/src/routes/printer/filament/[id]/+page.server.ts b/src/routes/printer/filament/[id]/+page.server.ts index 3bcac11..8a6544a 100644 --- a/src/routes/printer/filament/[id]/+page.server.ts +++ b/src/routes/printer/filament/[id]/+page.server.ts @@ -1,5 +1,5 @@ import type { PageServerLoad } from './$types'; -import { getFilamentByColor } from '$lib/server/database'; +import { getFilamentByColor } from '$lib/server/database/filament'; export const load = async ({ params }: Parameters[0]) => { let { id } = params;