83 lines
2.2 KiB
TypeScript
83 lines
2.2 KiB
TypeScript
import { cloneDeep } from 'lodash';
|
|
import { state } from '../db-admin/health-legacy';
|
|
import getUri, { intToTrkptId } from '../lib/ids';
|
|
import { appendToArray } from './gpx';
|
|
import { getFamily, put } from './lib';
|
|
import { compactRteOrTrksegDebounced } from './rte';
|
|
import { putNewTrk } from './trk';
|
|
import { emptyWpt } from './wpt';
|
|
|
|
const emptyTrkseg: Trkseg = {
|
|
trkpt: undefined,
|
|
extensions: undefined,
|
|
};
|
|
|
|
export const getTrksegDocs: ({
|
|
id,
|
|
}: {
|
|
id: string;
|
|
}) => Promise<{ docs: any; trkseg: Trkseg }> = async (params) => {
|
|
const { id } = params;
|
|
const docs = await getFamily(id, { include_docs: true });
|
|
let trkseg: Trkseg;
|
|
if (docs.rows.length === 1) {
|
|
trkseg = docs.rows[0].doc.doc;
|
|
} else {
|
|
trkseg = cloneDeep(docs.rows[0].doc.doc);
|
|
if (!trkseg.trkpt) {
|
|
trkseg.trkpt = [];
|
|
}
|
|
docs.rows.slice(1).forEach((row: any) => {
|
|
trkseg.trkpt.push(row.doc.doc);
|
|
});
|
|
}
|
|
console.log({
|
|
caller: 'getTrksegDocs',
|
|
id,
|
|
docs,
|
|
nbWptIn: docs.rows[0].doc.doc.trkpt?.length,
|
|
nbWptTotal: trkseg?.trkpt?.length,
|
|
});
|
|
return { docs, trkseg };
|
|
};
|
|
|
|
export const getTrkseg = async (params: any) => {
|
|
const { id } = params;
|
|
const { docs, trkseg } = await getTrksegDocs(params);
|
|
if (docs.rows.length > 1 && docs.rows[0].doc.origin === state().userId) {
|
|
// console.log({
|
|
// caller: 'getTrkseg compactRteOrTrksegDebounced required',
|
|
// id,
|
|
// });
|
|
compactRteOrTrksegDebounced({ id, getDocs: getTrksegDocs });
|
|
}
|
|
return trkseg;
|
|
};
|
|
|
|
export const putTrkseg = async (trkSegId: string, trkSeg = emptyTrkseg) => {
|
|
await put(
|
|
trkSegId,
|
|
'trkseg',
|
|
(doc) => {
|
|
return trkSeg;
|
|
},
|
|
emptyTrkseg
|
|
);
|
|
return trkSegId;
|
|
};
|
|
|
|
export const appendTrkpt = async (params: any) => {
|
|
const { trksegIdObj, trkpt } = params;
|
|
const idTrkseg = getUri('trkseg', trksegIdObj);
|
|
try {
|
|
await db.get(idTrkseg);
|
|
} catch {
|
|
await put(idTrkseg, 'trkseg', (doc) => doc, emptyTrkseg);
|
|
}
|
|
const trkptIdPart = intToTrkptId(new Date(trkpt.time as string).valueOf());
|
|
const trkptIdObj = { ...trksegIdObj, trkpt: trkptIdPart };
|
|
const trkptId = getUri('trkpt', trkptIdObj);
|
|
await put(trkptId, 'trkpt', (doc) => trkpt, emptyWpt);
|
|
return trkptId;
|
|
};
|