Fix: Auto-reconnect to SurrealDB on token expiration

This commit is contained in:
2026-03-15 20:11:56 -07:00
parent 11339a0900
commit 04bd2fada6

View File

@@ -7,8 +7,6 @@ class Database {
}
async connect() {
if (this.connected) return;
const url = process.env.SURREAL_URL;
const user = process.env.SURREAL_USER;
const pass = process.env.SURREAL_PASS;
@@ -20,7 +18,9 @@ class Database {
}
try {
if (!this.client) {
this.client = new Surreal();
}
await this.client.connect(url);
await this.client.signin({ username: user, password: pass });
await this.client.use({ namespace: 'kalbot', database: 'kalbot' });
@@ -44,6 +44,16 @@ class Database {
});
}
async _handleTokenExpiration(e) {
if (e.message && e.message.toLowerCase().includes('token has expired')) {
console.log('[DB] Session token expired! Attempting to re-authenticate...');
this.connected = false;
await this.connect();
return this.connected; // Returns true if reconnection was successful
}
return false;
}
async query(sql, vars = {}) {
if (!this.connected) return [[]];
@@ -51,6 +61,16 @@ class Database {
const raw = await this.client.query(sql, vars);
return this._normalizeQueryResult(raw);
} catch (e) {
// Check if it's an expiration issue, if so, reconnect and retry once
if (await this._handleTokenExpiration(e)) {
try {
const retryRaw = await this.client.query(sql, vars);
return this._normalizeQueryResult(retryRaw);
} catch (retryErr) {
console.error('[DB] Query retry error:', retryErr.message);
return [[]];
}
}
console.error('[DB] Query error:', e.message);
return [[]];
}
@@ -61,6 +81,14 @@ class Database {
try {
return await this.client.create(table, data);
} catch (e) {
if (await this._handleTokenExpiration(e)) {
try {
return await this.client.create(table, data);
} catch (retryErr) {
console.error('[DB] Create retry error:', retryErr.message);
return null;
}
}
console.error('[DB] Create error:', e.message);
return null;
}
@@ -71,6 +99,14 @@ class Database {
try {
return await this.client.select(table);
} catch (e) {
if (await this._handleTokenExpiration(e)) {
try {
return await this.client.select(table);
} catch (retryErr) {
console.error('[DB] Select retry error:', retryErr.message);
return [];
}
}
console.error('[DB] Select error:', e.message);
return [];
}