From c70fafeaa8b9ca5e0bc89a33bbce1fa816abc49b Mon Sep 17 00:00:00 2001 From: bootunloader Date: Thu, 30 Jan 2025 12:32:29 +0200 Subject: [PATCH] and so the db wars continue.... --- src/lib/server/connectors/surreal.db.ts | 61 +++++++++++++++++++------ 1 file changed, 47 insertions(+), 14 deletions(-) diff --git a/src/lib/server/connectors/surreal.db.ts b/src/lib/server/connectors/surreal.db.ts index 07e638e..05c06f9 100755 --- a/src/lib/server/connectors/surreal.db.ts +++ b/src/lib/server/connectors/surreal.db.ts @@ -2,29 +2,62 @@ import Surreal, { StringRecordId } from "surrealdb"; export type { QueryResult } from "surrealdb"; try { - if (document || window) { - throw new Error("SurrealDB needs a NodeJS environment to run."); - } + if (document || window) { + throw new Error("SurrealDB needs a NodeJS environment to run."); + } } catch (err) {} const CONFIG = { - url: process.env.SURREAL_URL ?? "", - user: process.env.SURREAL_USER ?? "", - pass: process.env.SURREAL_PASS ?? "", - ns: process.env.SURREAL_NS ?? "", - db: process.env.SURREAL_DB ?? "", + url: process.env.SURREAL_URL ?? "", + user: process.env.SURREAL_USER ?? "", + pass: process.env.SURREAL_PASS ?? "", + ns: process.env.SURREAL_NS ?? "", + db: process.env.SURREAL_DB ?? "", } as const; const db = new Surreal(); -export function parseToRID(idStr: string) { - return new StringRecordId(idStr); -} - -if (CONFIG.url.length > 0) { +async function connectDB() { + try { await db.connect(`http://${CONFIG.url}/rpc`); await db.use({ namespace: CONFIG.ns, database: CONFIG.db }); - await db.signin({ username: CONFIG.user, password: CONFIG.pass }); + await authenticateDB(); + } catch (error) { + console.error("Error connecting to SurrealDB:", error); + } } +async function authenticateDB() { + try { + await db.signin({ username: CONFIG.user, password: CONFIG.pass }); + console.log("🔑 Successfully authenticated with SurrealDB"); + } catch (error) { + console.error("❌ Authentication failed:", error); + } +} + +async function ensureAuthenticated() { + try { + console.log("⏳ Ensuring authentication with SurrealDB..."); + await db.query("RETURN 1"); + } catch (error) { + const e = error as any; + if (e.status === 401) { + console.warn("⚠️ Token expired. Re-authenticating..."); + await authenticateDB(); + } else { + console.error("Unexpected database error:", e); + } + } +} + +const MINS_5 = 5 * 60 * 1000; +setInterval(ensureAuthenticated, MINS_5); + +await connectDB(); + export const surreal = db as Surreal; + +export function parseToRID(idStr: string) { + return new StringRecordId(idStr); +}