and so the db wars continue....
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user