This commit is contained in:
bootunloader
2025-01-31 10:25:22 +02:00
parent c70fafeaa8
commit 15f62eaebf

View File

@@ -2,62 +2,98 @@ import Surreal, { StringRecordId } from "surrealdb";
export type { QueryResult } from "surrealdb"; export type { QueryResult } from "surrealdb";
try { try {
if (document || window) { if (document || window) {
throw new Error("SurrealDB needs a NodeJS environment to run."); throw new Error("SurrealDB needs a NodeJS environment to run.");
} }
} catch (err) {} } catch (err) { }
const CONFIG = { const CONFIG = {
url: process.env.SURREAL_URL ?? "", url: process.env.SURREAL_URL ?? "",
user: process.env.SURREAL_USER ?? "", user: process.env.SURREAL_USER ?? "",
pass: process.env.SURREAL_PASS ?? "", pass: process.env.SURREAL_PASS ?? "",
ns: process.env.SURREAL_NS ?? "", ns: process.env.SURREAL_NS ?? "",
db: process.env.SURREAL_DB ?? "", db: process.env.SURREAL_DB ?? "",
} as const; } as const;
const db = new Surreal(); const db = new Surreal();
async function connectDB() { async function connectDB() {
try { try {
await db.connect(`http://${CONFIG.url}/rpc`); await db.connect(`http://${CONFIG.url}/rpc`);
await db.use({ namespace: CONFIG.ns, database: CONFIG.db }); await db.use({ namespace: CONFIG.ns, database: CONFIG.db });
await authenticateDB(); await authenticateDB();
} catch (error) { return true;
console.error("Error connecting to SurrealDB:", error); } catch (error) {
} console.error("Error connecting to SurrealDB:", error);
return false;
}
} }
async function authenticateDB() { async function authenticateDB() {
try { try {
await db.signin({ username: CONFIG.user, password: CONFIG.pass }); await db.signin({ username: CONFIG.user, password: CONFIG.pass });
console.log("🔑 Successfully authenticated with SurrealDB"); console.log("🔑 Successfully authenticated with SurrealDB");
} catch (error) { return true;
console.error("❌ Authentication failed:", error); } catch (error) {
} console.error("❌ Authentication failed:", error);
return false;
}
} }
async function ensureAuthenticated() { async function ensureAuthenticated() {
try { try {
console.log("⏳ Ensuring authentication with SurrealDB..."); console.log("⏳ Ensuring authentication with SurrealDB...");
await db.query("RETURN 1"); await db.query("RETURN 1");
} catch (error) { } catch (error: any) {
const e = error as any; if (error.status === 401) {
if (e.status === 401) { console.warn("⚠️ Token expired. Attempting reconnection...");
console.warn("⚠️ Token expired. Re-authenticating..."); try {
await authenticateDB(); // Full reconnection instead of just re-authentication
} else { await db.close();
console.error("Unexpected database error:", e); const success = await connectDB();
if (success) {
console.log("✅ Successfully reconnected to database");
} else {
console.error("❌ Failed to reconnect to database");
}
} catch (reconnectError) {
console.error("❌ Reconnection failed:", reconnectError);
}
} else {
console.error("Unexpected database error:", error);
}
} }
}
} }
const MINS_5 = 5 * 60 * 1000; // 1 minute
setInterval(ensureAuthenticated, MINS_5); const CHECK_INTERVAL = 60 * 1000;
let intervalId: NodeJS.Timeout;
await connectDB(); async function initializeDB() {
const success = await connectDB();
if (success) {
// Only start the interval if initial connection was successful
intervalId = setInterval(ensureAuthenticated, CHECK_INTERVAL);
} else {
console.error("Failed to initialize database connection");
// Optionally implement retry logic here
}
}
export function cleanup() {
if (intervalId) {
clearInterval(intervalId);
}
return db.close();
}
await initializeDB();
export const surreal = db as Surreal; export const surreal = db as Surreal;
export function parseToRID(idStr: string) { export function parseToRID(idStr: string) {
return new StringRecordId(idStr); return new StringRecordId(idStr);
} }
process.on("SIGTERM", cleanup);
process.on("SIGINT", cleanup);