fokemal / server /dist /db /client.js
automindy's picture
Upload 603 files
31fb0af verified
Raw
History Blame Contribute Delete
3.22 kB
/**
* Turso/libSQL database client wrapper.
*
* Provides a thin wrapper on top of `@libsql/client` that mirrors the
* `better-sqlite3` API shapes used throughout the codebase, but async.
*
* Key patterns:
* db.prepare(sql).run(...args) β†’ await db.run(sql, args)
* db.prepare(sql).get(...args) β†’ await db.get(sql, args)
* db.prepare(sql).all(...args) β†’ await db.all(sql, args)
* db.exec(multiSql) β†’ await db.execMulti(multiSql)
* db.transaction(() => { ... })() β†’ await db.batch([...])
* db.pragma(...) β†’ await db.run('PRAGMA ...')
*/
import fs from 'fs';
import path from 'path';
import { createClient } from '@libsql/client';
let db = null;
function createTursoDb(client) {
return {
client,
async execute(sql, args = []) {
return client.execute({ sql, args });
},
async run(sql, args = []) {
const result = await client.execute({ sql, args });
return {
changes: result.rowsAffected,
lastInsertRowid: result.lastInsertRowid !== undefined ? Number(result.lastInsertRowid) : 0,
};
},
async get(sql, args = []) {
const result = await client.execute({ sql, args });
return result.rows[0] ?? undefined;
},
async all(sql, args = []) {
const result = await client.execute({ sql, args });
return result.rows;
},
async execMulti(sql) {
const statements = sql
.split(';')
.map(s => s.trim())
.filter(s => s.length > 0);
for (const stmt of statements) {
await client.execute(stmt);
}
},
async batch(statements) {
if (statements.length === 0)
return [];
return client.batch(statements, 'write');
},
};
}
/**
* Initialize the Turso client. Call once at startup.
* Uses TURSO_DATABASE_URL + TURSO_AUTH_TOKEN env vars.
* Falls back to a local file if TURSO_DATABASE_URL is not set (dev mode).
*/
export function initClient(url) {
const dbUrl = url ?? process.env.TURSO_DATABASE_URL ?? 'file:./data/freeapi.db';
if (process.env.NODE_ENV === 'production' && !process.env.TURSO_DATABASE_URL && !url) {
console.warn('\n[WARNING] TURSO_DATABASE_URL is not set in production. Falling back to local SQLite database. Any changes will be lost when the container restarts!\n');
}
if (dbUrl.startsWith('file:')) {
const filePath = dbUrl.slice(5);
const dir = path.dirname(filePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
const authToken = process.env.TURSO_AUTH_TOKEN;
const client = createClient({
url: dbUrl,
authToken: authToken || undefined,
});
db = createTursoDb(client);
return db;
}
/** Get the initialized database wrapper. Throws if not yet created. */
export function getDb() {
if (!db) {
throw new Error('Database not initialized. Call initClient() first.');
}
return db;
}
//# sourceMappingURL=client.js.map