dyomedea/src/db/change-handler.ts

63 lines
1.6 KiB
TypeScript

import { getWpt } from '../db/wpt';
import { returnAgain } from '../workers/dispatcher-worker';
import { getAllGpxes, getGpx } from './gpx';
import { getRte } from './rte';
import { getTrk } from './trk';
import { getTrkseg } from './trkseg';
declare global {
var watches: Map<string, any>;
}
const methods = {
getAllGpxes,
getGpx,
getTrk,
getTrkseg,
getWpt,
getRte,
};
const sendUpdate = async (params: any) => {
if (params) {
console.log({ caller: 'ChangeHandler / sendUpdate', params });
const { method, _dispatchId, id, ...otherParams } = params;
const returnValue = await methods[<keyof typeof methods>method](params);
if (returnValue) {
returnAgain(_dispatchId, returnValue);
}
}
};
const changeHandler = async (change: any) => {
console.log({ caller: 'ChangeHandler', change });
const { id } = change;
if (!globalThis.watches) {
globalThis.watches = new Map();
}
sendUpdate(globalThis.watches.get(id));
const parentId = id.substring(0, id.lastIndexOf('/'));
sendUpdate(globalThis.watches.get(parentId));
};
export default changeHandler;
export const getAndWatch = async (params: any) => {
const { method, _dispatchId, id, ...otherParams } = params;
if (!globalThis.watches) {
globalThis.watches = new Map();
}
globalThis.watches.set(id, params);
const returnValue = await methods[<keyof typeof methods>method](params);
return returnValue;
};
export const cancelWatch = (params: any) => {
if (!globalThis.watches) {
globalThis.watches = new Map();
}
const { id } = params;
globalThis.watches.delete(id);
};