Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

paced-per-record.ts

47 lines1.7 KB

1import type { Transaction } from "@tanstack/react-db";
2​
3/**
4 * Keeps one paced mutation per record, shared by everything that changes it.
5 * A paced mutation saves its transactions one after another, in order, but
6 * only its own: two paced mutations (or a paced one and a direct update) for
7 * the same record could overlap, and the older one's unsaved state would
8 * cover the newer one's. Sharing one per record avoids that.
9 *
10 * It's created on first use and dropped once its last transaction settles.
11 */
12export function pacedPerRecord<TVariables, T extends object>(
13 create: (id: string) => (variables: TVariables) => Transaction<T>,
14) {
15 const instances = new Map<
16 string,
17 { mutate: (variables: TVariables) => Transaction<T>; unsettled: Set<Transaction<T>> }
18 >();
19​
20 return {
21 mutate(id: string, variables: TVariables): Transaction<T> {
22 let instance = instances.get(id);
23 if (!instance) {
24 instance = { mutate: create(id), unsettled: new Set() };
25 instances.set(id, instance);
26 }
27 const { mutate, unsettled } = instance;
28 const transaction = mutate(variables);
29 if (!unsettled.has(transaction)) {
30 unsettled.add(transaction);
31 const settled = () => {
32 unsettled.delete(transaction);
33 if (unsettled.size === 0 && instances.get(id) === instance) instances.delete(id);
34 };
35 transaction.when("settled").then(settled, settled);
36 }
37 return transaction;
38 },
39​
40 /** Rolls back the record's changes that haven't started saving yet. */
41 cancelPending(id: string) {
42 for (const transaction of instances.get(id)?.unsettled ?? []) {
43 if (transaction.state === "pending") transaction.rollback();
44 }
45 },
46 };