Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

OfflineTransaction.ts

123 lines3.7 KB

1import { createTransaction } from '@tanstack/db'
2import { NonRetriableError } from '../types'
3import type { PendingMutation, Transaction } from '@tanstack/db'
4import type {
5 CreateOfflineTransactionOptions,
6 OfflineMutationFn,
7 OfflineTransaction as OfflineTransactionType,
8} from '../types'
9​
10export class OfflineTransaction {
11 private offlineId: string
12 private mutationFnName: string
13 private autoCommit: boolean
14 private idempotencyKey: string
15 private metadata: Record<string, any>
16 private transaction: Transaction | null = null
17 private persistTransaction: (tx: OfflineTransactionType) => Promise<void>
18 private executor: any // Will be typed properly - reference to OfflineExecutor
19​
20 constructor(
21 options: CreateOfflineTransactionOptions,
22 mutationFn: OfflineMutationFn,
23 persistTransaction: (tx: OfflineTransactionType) => Promise<void>,
24 executor: any,
25 ) {
26 this.offlineId = crypto.randomUUID()
27 this.mutationFnName = options.mutationFnName
28 this.autoCommit = options.autoCommit ?? true
29 this.idempotencyKey = options.idempotencyKey ?? crypto.randomUUID()
30 this.metadata = options.metadata ?? {}
31 this.persistTransaction = persistTransaction
32 this.executor = executor
33 }
34​
35 mutate(callback: () => void): Transaction {
36 this.transaction = createTransaction({
37 id: this.offlineId,
38 autoCommit: false,
39 mutationFn: async () => {
40 // This is the blocking mutationFn that waits for the executor
41 // First persist the transaction to the outbox
42 const offlineTransaction: OfflineTransactionType = {
43 id: this.offlineId,
44 mutationFnName: this.mutationFnName,
45 mutations: this.transaction!.mutations,
46 keys: this.extractKeys(this.transaction!.mutations),
47 idempotencyKey: this.idempotencyKey,
48 createdAt: new Date(),
49 retryCount: 0,
50 nextAttemptAt: Date.now(),
51 metadata: this.metadata,
52 spanContext: undefined,
53 version: 1,
54 }
55​
56 const completionPromise = this.executor.waitForTransactionCompletion(
57 this.offlineId,
58 )
59​
60 try {
61 await this.persistTransaction(offlineTransaction)
62 // Now block and wait for the executor to complete the real mutation
63 await completionPromise
64 } catch (error) {
65 const normalizedError =
66 error instanceof Error ? error : new Error(String(error))
67 this.executor.rejectTransaction(this.offlineId, normalizedError)
68 throw error
69 }
70​
71 return
72 },
73 metadata: this.metadata,
74 })
75​
76 this.transaction.mutate(() => {
77 callback()
78 })
79​
80 if (this.autoCommit) {
81 // Auto-commit for direct OfflineTransaction usage
82 this.commit().catch((error) => {
83 console.error(`Auto-commit failed:`, error)
84 throw error
85 })
86 }
87​
88 return this.transaction
89 }
90​
91 async commit(): Promise<Transaction> {
92 if (!this.transaction) {
93 throw new Error(`No mutations to commit. Call mutate() first.`)
94 }
95​
96 try {
97 // Commit the TanStack DB transaction
98 // This will trigger the mutationFn which handles persistence and waiting
99 await this.transaction.commit()
100 return this.transaction
101 } catch (error) {
102 // Only rollback for NonRetriableError - other errors should allow retry
103 if (error instanceof NonRetriableError) {
104 this.transaction.rollback()
105 }
106 throw error
107 }
108 }
109​
110 rollback(): void {
111 if (this.transaction) {
112 this.transaction.rollback()
113 }
114 }
115​
116 private extractKeys(mutations: Array<PendingMutation>): Array<string> {
117 return mutations.map((mutation) => mutation.globalKey)
118 }
119​
120 get id(): string {
121 return this.offlineId
122 }