dyomedea/src/db/index.ts

94 lines
2.4 KiB
TypeScript

import _ from 'lodash';
const DBDEFINITION = '--db-definition--';
const dbDefinition = {
_id: DBDEFINITION,
type: DBDEFINITION,
version: '0.000001',
};
export const initDb = async (db: any, setDbReady: any) => {
try {
await db.get(DBDEFINITION);
// TODO: support migrations
} catch (error: any) {
if (error.status !== 404) {
console.log(
`Unexpected error fetching db definition: ${JSON.stringify(error)}`
);
return;
}
}
// WARNING: defs must use the canonical form and be identical to what will be returned by db.getIndexes
const requiredIndexes: any = [
{
name: 'type-subtype',
def: {
fields: [{ type: 'asc' }, { subtype: 'asc' }],
},
},
{
name: 'type-trkpt-gpx-time',
def: {
fields: [{ type: 'asc' }, { gpx: 'asc' }, { 'trkpt.time': 'asc' }],
},
},
];
const existingIndexes = (await db.getIndexes()).indexes;
const pruneIndex = ({ name, def }: any) => ({ name, def });
const isSameIndex = (idx1: any, idx2: any) => {
return _.isEqual(pruneIndex(idx1), pruneIndex(idx2));
};
const findIndex = (targetIndexes: any, index: any) =>
targetIndexes.find((targetIndex: any) => {
return isSameIndex(targetIndex, index);
});
for (var index of existingIndexes) {
if (index.type === 'json') {
// Non system indexes
console.log(`Checking existing index :${JSON.stringify(index)}`);
if (!findIndex(requiredIndexes, index)) {
console.log(`db.deleteIndex(${JSON.stringify(index)})`);
await db.deleteIndex(index);
}
}
}
for (var index of requiredIndexes) {
if (!findIndex(existingIndexes, index)) {
console.log(`db.createIndex(${JSON.stringify(index)})`);
await db.createIndex({ name: index.name, ...index.def });
}
}
setDbReady(true);
const indexes = await db.getIndexes();
console.log(`indexes: ${JSON.stringify(indexes)}`);
const explain1 = await db.explain({
selector: {
type: 'trkpt',
gpx: 'xxxx',
},
// sort: ['trkpt.time'],
// use_index: 'type-trkpt-gpx-time',
});
console.log(`explain1: ${JSON.stringify(explain1)}`);
const explain2 = await db.explain({
selector: {
type: 'gpx',
},
// sort: ['trkpt.time'],
// use_index: 'type-trkpt-gpx-time',
});
console.log(`explain2: ${JSON.stringify(explain2)}`);
};