/** * Database service using express-pouchdb for self-hosted database sync. * Provides PouchDB HTTP API compatible with client-side PouchDB replication. */ import PouchDB from 'pouchdb'; import PouchDBAdapterMemory from 'pouchdb-adapter-memory'; import expressPouchdb from 'express-pouchdb'; import path from 'path'; import { fileURLToPath } from 'url'; // Register memory adapter (works in Node.js without leveldown issues) PouchDB.plugin(PouchDBAdapterMemory); const __dirname = path.dirname(fileURLToPath(import.meta.url)); // Data directory for persistent storage (used for logs) const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '../../data'); // Use memory adapter for now - data persists while server is running // TODO: Switch to leveldb once version conflicts are resolved const memPouchDB = PouchDB.defaults({ adapter: 'memory' }); // Create express-pouchdb middleware // Using 'minimumForPouchDB' mode for lightweight operation // Include routes needed for PouchDB replication const pouchApp = expressPouchdb(memPouchDB, { mode: 'minimumForPouchDB', overrideMode: { include: [ 'routes/root', // GET / - server info 'routes/db', // PUT/GET/DELETE /:db 'routes/all-dbs', // GET /_all_dbs 'routes/changes', // GET /:db/_changes 'routes/bulk-docs', // POST /:db/_bulk_docs 'routes/bulk-get', // POST /:db/_bulk_get 'routes/all-docs', // GET /:db/_all_docs 'routes/revs-diff', // POST /:db/_revs_diff 'routes/documents' // GET/PUT/DELETE /:db/:docid ] }, logPath: path.join(DATA_DIR, 'logs', 'pouchdb.log') }); console.log(`[Database] Initialized express-pouchdb with data dir: ${DATA_DIR}`); // Test that PouchDB can create databases (async () => { try { const testDb = new memPouchDB('_test_db'); const info = await testDb.info(); console.log('[Database] Test DB created successfully:', info); await testDb.destroy(); console.log('[Database] Test DB destroyed'); } catch (err) { console.error('[Database] Failed to create test database:', err); } })(); export { memPouchDB as PouchDB, pouchApp };