Open History to see the last commit
1import { OnMutateMustBeSynchronousError } from '@tanstack/db'
2import { OfflineTransaction } from './OfflineTransaction'
3import type { Transaction } from '@tanstack/db'
4import type {
5 CreateOfflineActionOptions,
6 OfflineMutationFn,
7 OfflineTransaction as OfflineTransactionType,
8} from '../types'
9
10function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
11 return (
12 !!value &&
13 (typeof value === `object` || typeof value === `function`) &&
14 typeof (value as { then?: unknown }).then === `function`
15 )
16}
17
18export function createOfflineAction<T>(
19 options: CreateOfflineActionOptions<T>,
20 mutationFn: OfflineMutationFn,
21 persistTransaction: (tx: OfflineTransactionType) => Promise<void>,
22 executor: any,
23): (variables: T) => Transaction {
24 const { mutationFnName, onMutate } = options
25
26 return (variables: T): Transaction => {
27 const offlineTransaction = new OfflineTransaction(
28 {
29 mutationFnName,
30 // The transaction commits after onMutate and reports a failure
31 // through `when('settled')`.
32 autoCommit: true,
33 },
34 mutationFn,
35 persistTransaction,
36 executor,
37 )
38
39 return offlineTransaction.mutate(() => {
40 const maybePromise = onMutate(variables) as unknown
41
42 if (isPromiseLike(maybePromise)) {
43 throw new OnMutateMustBeSynchronousError()
44 }
45 })
46 }
47}