import _ from 'lodash'; import PouchDB from 'pouchdb'; import uri from '../lib/ids'; import changeHandler from './change-handler'; const dbDefinitionId = uri('dbdef', {}); const currentDbDefinition = { _id: dbDefinitionId, type: dbDefinitionId, def: { version: '0.000001' }, }; declare global { var db: any; var dbReady: boolean; } export const initDb = async (params: any) => { console.log({ caller: 'initDb' }); if (globalThis.db === undefined) { globalThis.db = new PouchDB('dyomedea', { auto_compaction: false, // revs_limit: 10, }); } const db = globalThis.db; var previousDbDefinition = { _id: dbDefinitionId, type: dbDefinitionId, def: { version: '0' }, }; try { previousDbDefinition = await db.get(dbDefinitionId); } catch (error: any) { if (error.status !== 404) { console.log( `Unexpected error fetching db definition: ${JSON.stringify(error)}` ); return; } } if (previousDbDefinition.def.version < currentDbDefinition.def.version) { previousDbDefinition.def = currentDbDefinition.def; db.put(previousDbDefinition); // TODO: support migrations } //await await db.compact(); globalThis.dbReady = true; console.log({ caller: 'initDb / before db.changes' }); const changes = db .changes({ since: 'now', live: true, include_docs: false }) .on('change', changeHandler) .on('complete', (info: any) => { console.log({ caller: 'changes / complete', info }); }) .on('error', (error: any) => { console.log({ caller: 'changes / complete', error }); }); // console.log({ caller: 'initDb / back from db.changes', changes }); // changes.cancel(); };