refactor: cargar bun:sqlite dinámicamente y añadir getDb

Co-authored-by: aider (openrouter/openai/gpt-5) <aider@aider.chat>
webui
brobert 2 weeks ago
parent 94bbb5ad1b
commit 296ab169f1

@ -1,9 +1,8 @@
import { Database } from 'bun:sqlite';
import { mkdirSync } from 'fs';
import { dirname } from 'path';
import { resolveDbAbsolutePath } from './env';
function applyDefaultPragmas(instance: Database): void {
function applyDefaultPragmas(instance: any): void {
try {
instance.exec(`PRAGMA busy_timeout = 5000;`);
// Intentar activar WAL (si no es soportado, SQLite devolverá 'memory' u otro modo)
@ -19,8 +18,9 @@ function applyDefaultPragmas(instance: Database): void {
/**
* Abre la BD compartida sin ejecutar migraciones (las realiza el proceso del bot).
* Nota: uso de import dinámico de 'bun:sqlite' para que el build con Node no falle.
*/
export function openDb(filename: string = 'tasks.db'): Database {
async function openDb(filename: string = 'tasks.db'): Promise<any> {
const absolutePath = resolveDbAbsolutePath(filename);
// Crear directorio padre si no existe
@ -30,10 +30,19 @@ export function openDb(filename: string = 'tasks.db'): Database {
if (err?.code !== 'EEXIST') throw err;
}
const { Database } = await import('bun:sqlite');
const instance = new Database(absolutePath);
applyDefaultPragmas(instance);
return instance;
}
// Instancia por defecto
export const db = openDb();
let _db: any | null = null;
/**
* Devuelve una única instancia compartida (lazy) de la BD.
*/
export async function getDb(filename: string = 'tasks.db'): Promise<any> {
if (_db) return _db;
_db = await openDb(filename);
return _db;
}

@ -1,6 +1,6 @@
import type { RequestHandler } from './$types';
import { redirect } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import { getDb } from '$lib/server/db';
import { sha256Hex, randomTokenBase64Url } from '$lib/server/crypto';
import { sessionIdleTtlMs, isProd } from '$lib/server/env';
@ -18,6 +18,8 @@ export const GET: RequestHandler = async (event) => {
const tokenHash = await sha256Hex(token);
const nowIso = toIsoSql(new Date());
const db = await getDb();
// Intentar canjear el token: marcarlo como usado si está vigente y no usado
const res = db
.prepare(

@ -2,5 +2,13 @@ import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit()]
plugins: [sveltekit()],
ssr: {
// Evita que Node intente resolver el esquema 'bun:' durante el build SSR
external: ['bun:sqlite']
},
optimizeDeps: {
// No prebundlear 'bun:sqlite' en dev
exclude: ['bun:sqlite']
}
});

Loading…
Cancel
Save