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

TransactionSerializer.ts

173 lines5.1 KB

1import type {
2 OfflineTransaction,
3 SerializedError,
4 SerializedMutation,
5 SerializedOfflineTransaction,
6} from '../types'
7import type { Collection, PendingMutation } from '@tanstack/db'
8​
9export class TransactionSerializer {
10 private collections: Record<string, Collection<any, any, any, any, any>>
11 private collectionIdToKey: Map<string, string>
12​
13 constructor(
14 collections: Record<string, Collection<any, any, any, any, any>>,
15 ) {
16 this.collections = collections
17 // Create reverse lookup from collection.id to registry key
18 this.collectionIdToKey = new Map()
19 for (const [key, collection] of Object.entries(collections)) {
20 this.collectionIdToKey.set(collection.id, key)
21 }
22 }
23​
24 serialize(transaction: OfflineTransaction): string {
25 const serialized: SerializedOfflineTransaction = {
26 ...transaction,
27 createdAt: transaction.createdAt.toISOString(),
28 mutations: transaction.mutations.map((mutation) =>
29 this.serializeMutation(mutation),
30 ),
31 }
32 return JSON.stringify(serialized)
33 }
34​
35 deserialize(data: string): OfflineTransaction {
36 // Parse without a reviver - let deserializeValue handle dates in mutation data
37 // using the { __type: 'Date' } marker system
38 const parsed: SerializedOfflineTransaction = JSON.parse(data)
39​
40 const createdAt = new Date(parsed.createdAt)
41 if (isNaN(createdAt.getTime())) {
42 throw new Error(
43 `Failed to deserialize transaction: invalid createdAt value "${parsed.createdAt}"`,
44 )
45 }
46​
47 return {
48 ...parsed,
49 createdAt,
50 mutations: parsed.mutations.map((mutationData) =>
51 this.deserializeMutation(mutationData),
52 ),
53 }
54 }
55​
56 private serializeMutation(mutation: PendingMutation): SerializedMutation {
57 const registryKey = this.collectionIdToKey.get(mutation.collection.id)
58 if (!registryKey) {
59 throw new Error(
60 `Collection with id ${mutation.collection.id} not found in registry`,
61 )
62 }
63​
64 return {
65 globalKey: mutation.globalKey,
66 type: mutation.type,
67 modified: this.serializeValue(mutation.modified),
68 original: this.serializeValue(mutation.original),
69 changes: this.serializeValue(mutation.changes),
70 collectionId: registryKey, // Store registry key instead of collection.id
71 }
72 }
73​
74 private deserializeMutation(data: SerializedMutation): PendingMutation {
75 const collection = this.collections[data.collectionId]
76 if (!collection) {
77 throw new Error(`Collection with id ${data.collectionId} not found`)
78 }
79​
80 const modified = this.deserializeValue(data.modified)
81​
82 // Extract the key from the modified data using the collection's getKey function
83 // This is needed for optimistic state restoration to work correctly
84 const key = modified ? collection.getKeyFromItem(modified) : null
85​
86 // Create a partial PendingMutation - we can't fully reconstruct it but
87 // we provide what we can. The executor will need to handle the rest.
88 return {
89 globalKey: data.globalKey,
90 type: data.type as any,
91 modified,
92 original: this.deserializeValue(data.original),
93 changes: this.deserializeValue(data.changes) ?? {},
94 collection,
95 // These fields would need to be reconstructed by the executor
96 mutationId: ``, // Will be regenerated
97 key,
98 metadata: undefined,
99 syncMetadata: {},
100 optimistic: true,
101 createdAt: new Date(),
102 updatedAt: new Date(),
103 } as PendingMutation
104 }
105​
106 private serializeValue(value: any): any {
107 if (value === null || value === undefined) {
108 return value
109 }
110​
111 if (value instanceof Date) {
112 return { __type: `Date`, value: value.toISOString() }
113 }
114​
115 if (typeof value === `object`) {
116 const result: any = Array.isArray(value) ? [] : {}
117 for (const key in value) {
118 if (Object.prototype.hasOwnProperty.call(value, key)) {
119 result[key] = this.serializeValue(value[key])
120 }
121 }
122 return result
123 }
124​
125 return value
126 }
127​
128 private deserializeValue(value: any): any {
129 if (value === null || value === undefined) {
130 return value
131 }
132​
133 if (typeof value === `object` && value.__type === `Date`) {
134 if (value.value === undefined || value.value === null) {
135 throw new Error(`Corrupted Date marker: missing value field`)
136 }
137 const date = new Date(value.value)
138 if (isNaN(date.getTime())) {
139 throw new Error(
140 `Failed to deserialize Date marker: invalid date value "${value.value}"`,
141 )
142 }
143 return date
144 }
145​
146 if (typeof value === `object`) {
147 const result: any = Array.isArray(value) ? [] : {}
148 for (const key in value) {
149 if (Object.prototype.hasOwnProperty.call(value, key)) {
150 result[key] = this.deserializeValue(value[key])
151 }
152 }
153 return result
154 }
155​
156 return value
157 }
158​
159 serializeError(error: Error): SerializedError {
160 return {
161 name: error.name,
162 message: error.message,
163 stack: error.stack,
164 }
165 }
166​
167 deserializeError(data: SerializedError): Error {
168 const error = new Error(data.message)
169 error.name = data.name
170 error.stack = data.stack
171 return error
172 }