Save scheduler changes to a serverScheduler
Persist every scheduler edit from historyChange, batch requests, roll back changes the server rejects, and apply updates from other users without echoing them back.
The scheduler applies a user's change to its own copy of the data and then tells you about it. Saving is up to you. This recipe sends each change to a REST API in small batches, undoes changes the server refuses, and applies changes pushed by other dispatchers without sending them back.
Choose the events to listen to#
| Approach | Listen to | Use it when |
|---|---|---|
| Per action | eventDrop, eventResize, eventRemove, plus historyChange for undo and redo |
Your API has one endpoint per action, such as "reschedule job". |
| Per change | historyChange only |
Your API stores events. One listener covers moves, resizes, removals, API edits, undo, redo and recurring series. |
This recipe uses the second approach. The first is shown in Keeping a server in sync.
Steps#
- Collect
{ id, after }pairs fromhistoryChangeinto a pending map, so several edits to one job become one request. - Flush the map after a short pause.
- When the server rejects the batch, call
undo()and tell the user. - Apply changes from other users with a flag set, so the listener skips them.
Save in batches#
schedule-sync.ts
import type { SchedulerApi } from '@birchui/scheduler';
type JobPatch = { id: string; job: WorkOrder | null };
export function syncToServer(scheduler: SchedulerApi<WorkOrder, Technician>, notify: (message: string) => void) {
const pending = new Map<string, WorkOrder | null>();
let timer: ReturnType<typeof setTimeout> | undefined;
let applyingRemote = false;
async function flush() {
const batch: JobPatch[] = [...pending].map(([id, job]) => ({ id, job }));
pending.clear();
if (batch.length === 0) return;
const response = await fetch('/api/dispatch/jobs', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch),
});
if (response.ok) return;
const { message } = (await response.json().catch(() => ({ message: 'The change could not be saved.' }))) as {
message: string;
};
applyingRemote = true;
scheduler.undo();
applyingRemote = false;
notify(message);
}
const off = scheduler.on('historyChange', ({ action, changes }) => {
if (action === 'clear' || applyingRemote) return;
for (const { id, after } of changes) pending.set(id, after);
clearTimeout(timer);
timer = setTimeout(() => void flush(), 400);
});
function applyRemote(update: JobPatch) {
applyingRemote = true;
try {
if (!update.job) scheduler.removeEvent(update.id);
else if (scheduler.getEventById(update.id)) scheduler.updateEvent(update.id, update.job);
else scheduler.addEvent(update.job);
} finally {
applyingRemote = false;
}
}
return { applyRemote, stop: off };
}Wire it to a WebSocket or server-sent events stream:
dispatch-board.ts
const sync = syncToServer(scheduler, showToast);
const stream = new EventSource('/api/dispatch/stream');
stream.addEventListener('job', (message) => sync.applyRemote(JSON.parse(message.data)));The server side#
The server receives the full event for each id, or null for a removal. Validate it there too: client-side rules can be bypassed.
server/dispatch-jobs.ts
app.patch('/api/dispatch/jobs', async (request, response) => {
const batch = request.body as { id: string; job: WorkOrder | null }[];
for (const { id, job } of batch) {
if (job && (await jobs.overlapsForTechnician(job.resourceId, job.start, job.end, id))) {
return response.status(409).json({ message: `${job.title} overlaps another job for this technician.` });
}
}
await db.transaction(async (tx) => {
for (const { id, job } of batch) {
if (job) await tx.jobs.upsert({ ...job, id });
else await tx.jobs.delete(id);
}
});
broadcast(batch);
response.status(204).end();
});How it works#
historyChangefires once per recorded step with every event it touched.afteris the event as it is now, ornullwhen it was removed, so one upsert-or-delete loop handles all kinds of edits.- Moving one occurrence of a recurring series yields two changes: the master with a new
exdatesentry, and the detached occurrence. Both are saved by the same loop. See Schedule recurring maintenance jobs. - Because
undo()reverses the last step, the rejected change disappears from the screen and from the history, andhistoryChangefires withaction: 'undo'. TheapplyingRemoteflag stops that undo from being sent back to the server. - Remote updates applied with
addEvent,updateEventandremoveEventare recorded in the history as well. Skipping them in the listener keeps the server from receiving its own data.
Pitfalls#
- History must be on.
historyChangedoes not fire withundoRedo: false. Keep the default or set alimit. - Undo after several batches.
undo()reverses only the latest step. If the user made another change before the server answered, that change is undone instead. For busy boards, save each change on its own and roll back withupdateEvent(id, before)from thehistoryChangepayload. - Remote updates join the user's undo stack. A dispatcher pressing Ctrl + Z can undo a colleague's change. If that matters, call
setEvents()with fresh data for large remote updates, which starts a new history. - Dates on the wire.
after.startandafter.endareDateobjects after a drag.JSON.stringifywrites them as UTC ISO strings.
Related#
- Validate scheduler drag and drop to block invalid changes before they happen.
- Undo and redo in the scheduler.
- Updating data.