import { PureComponent } from 'react'; import getUri, { intToGpxId } from '../lib/ids'; import { get, put, putAll } from './lib'; const emptyGpx: Gpx = { $: { version: '1.1', creator: 'dyomedea version 0.000002', xmlns: 'http://www.topografix.com/GPX/1/1', 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation': 'http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www8.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/WaypointExtension/v1 http://www8.garmin.com/xmlschemas/WaypointExtensionv1.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd', 'xmlns:gpxx': 'http://www.garmin.com/xmlschemas/GpxExtensions/v3', 'xmlns:wptx1': 'http://www.garmin.com/xmlschemas/WaypointExtension/v1', 'xmlns:gpxtpx': 'http://www.garmin.com/xmlschemas/TrackPointExtension/v1', 'xmlns:dyo': 'http://xmlns.dyomedea.com/', }, metadata: { name: undefined, desc: undefined, author: undefined, copyright: undefined, link: undefined, time: undefined, keywords: undefined, bounds: undefined, extensions: undefined, }, wpt: undefined, rte: undefined, trk: undefined, extensions: undefined, }; export const putNewGpx = async ( id: IdGpx = { gpx: intToGpxId(Date.now()) } ) => { const uri = getUri('gpx', id); await put( uri, 'gpx', (gpx) => { (gpx.metadata ??= {}).time = new Date(Date.now()).toISOString(); return gpx; }, emptyGpx ); return id; }; export const existsGpx = async (id: IdGpx) => { const uri = getUri('gpx', id); try { await get(uri); return true; } catch { return false; } }; const prune = (id: any, object: any, docs: any[]) => { if (typeof object === 'object') { for (const key in object) { if ( key === 'wpt' || key === 'rte' || key === 'rtept' || key === 'trk' || key === 'trkseg' || key === 'trkpt' ) { const subObjects = object[key]; for (const index in subObjects) { const subId = { ...id }; subId[key] = index; docs.push({ _id: getUri(key, subId), type: key, doc: subObjects[index], }); prune(subId, subObjects[index], docs); } object[key] = undefined; } else prune(id, object[key], docs); } } }; export const pruneAndSaveImportedGpx = async (params: any) => { const { id, gpx } = params; let docs: any[] = [{ _id: getUri('gpx', id), type: 'gpx', doc: gpx }]; prune(id, gpx, docs); console.log(JSON.stringify(docs)); try { const result = await putAll(docs); console.log(JSON.stringify(result)); } catch (err) { console.error(`error: ${err}`); } };