@@ -12,24 +12,13 @@ import type {
1212const transactions : Array < Transaction < any > > = [ ]
1313let transactionStack : Array < Transaction < any > > = [ ]
1414
15+ let sequenceNumber = 0
16+
1517export function createTransaction <
1618 TData extends object = Record < string , unknown > ,
1719> ( config : TransactionConfig < TData > ) : Transaction < TData > {
18- if ( typeof config . mutationFn === `undefined` ) {
19- throw `mutationFn is required when creating a transaction`
20- }
21-
22- let transactionId = config . id
23- if ( ! transactionId ) {
24- transactionId = crypto . randomUUID ( )
25- }
26- const newTransaction = new Transaction < TData > ( {
27- ...config ,
28- id : transactionId ,
29- } )
30-
20+ const newTransaction = new Transaction < TData > ( config )
3121 transactions . push ( newTransaction )
32-
3322 return newTransaction
3423}
3524
@@ -56,7 +45,7 @@ function removeFromPendingList(tx: Transaction<any>) {
5645 }
5746}
5847
59- export class Transaction <
48+ class Transaction <
6049 T extends object = Record < string , unknown > ,
6150 TOperation extends OperationType = OperationType ,
6251> {
@@ -67,20 +56,25 @@ export class Transaction<
6756 public isPersisted : Deferred < Transaction < T , TOperation > >
6857 public autoCommit : boolean
6958 public createdAt : Date
59+ public sequenceNumber : number
7060 public metadata : Record < string , unknown >
7161 public error ?: {
7262 message : string
7363 error : Error
7464 }
7565
7666 constructor ( config : TransactionConfig < T > ) {
77- this . id = config . id !
67+ if ( typeof config . mutationFn === `undefined` ) {
68+ throw `mutationFn is required when creating a transaction`
69+ }
70+ this . id = config . id ?? crypto . randomUUID ( )
7871 this . mutationFn = config . mutationFn
7972 this . state = `pending`
8073 this . mutations = [ ]
8174 this . isPersisted = createDeferred < Transaction < T , TOperation > > ( )
8275 this . autoCommit = config . autoCommit ?? true
8376 this . createdAt = new Date ( )
77+ this . sequenceNumber = sequenceNumber ++
8478 this . metadata = config . metadata ?? { }
8579 }
8680
@@ -210,4 +204,21 @@ export class Transaction<
210204
211205 return this
212206 }
207+
208+ /**
209+ * Compare two transactions by their createdAt time and sequence number in order
210+ * to sort them in the order they were created.
211+ * @param other - The other transaction to compare to
212+ * @returns -1 if this transaction was created before the other, 1 if it was created after, 0 if they were created at the same time
213+ */
214+ compareCreatedAt ( other : Transaction < any > ) : number {
215+ const createdAtComparison =
216+ this . createdAt . getTime ( ) - other . createdAt . getTime ( )
217+ if ( createdAtComparison !== 0 ) {
218+ return createdAtComparison
219+ }
220+ return this . sequenceNumber - other . sequenceNumber
221+ }
213222}
223+
224+ export type { Transaction }
0 commit comments