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

write-queue.ts

41 lines1.6 KB

1/**
2 * Two small helpers the collection handlers use to save safely.
3 */
4​
5const lastWrite = new Map<string, Promise<unknown>>();
6​
7/**
8 * Runs the writes for one record (keyed by its URL) one at a time, in the
9 * order the handlers asked for them. A write here is the request and the
10 * confirmed row it writes back, so an older save can't reach the server,
11 * or the collection, after a newer one. Optimistic updates don't wait: only
12 * the requests do.
13 *
14 * If a write fails, the writes queued behind it for the same record fail
15 * too, without being sent: they were made on top of a change the server
16 * rejected (TanStack DB rolls those transactions back as well).
17 */
18export function inOrder<T>(resource: string, write: () => Promise<T>): Promise<T> {
19 const next = (lastWrite.get(resource) ?? Promise.resolve()).then(write);
20 lastWrite.set(resource, next);
21 const forget = () => {
22 if (lastWrite.get(resource) === next) lastWrite.delete(resource);
23 };
24 next.then(forget, forget);
25 return next;
27​
28/**
29 * Saves every mutation of a transaction and waits for all of them, then
30 * throws the first error, if any. Unlike `Promise.all`, one rejected record
31 * doesn't stop the others from being confirmed: the transaction still rolls
32 * back, but records the server accepted keep their saved values.
33 */
34export async function saveEach<TMutation>(
35 mutations: TMutation[],
36 save: (mutation: TMutation) => Promise<void>,
37): Promise<void> {
38 const results = await Promise.allSettled(mutations.map(save));
39 const failure = results.find((result) => result.status === "rejected");
40 if (failure) throw failure.reason;