/
transaction.ts
515 lines (478 loc) · 15.6 KB
/
transaction.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as proto from '../protos/firestore_proto_api';
import {DocumentSnapshot, Precondition} from './document';
import {Firestore, WriteBatch} from './index';
import {FieldPath, validateFieldPath} from './path';
import {
DocumentReference,
Query,
QuerySnapshot,
validateDocumentReference,
} from './reference';
import {isPlainObject} from './serializer';
import {
DocumentData,
Precondition as PublicPrecondition,
ReadOptions,
SetOptions,
UpdateData,
} from './types';
import {isObject, requestTag} from './util';
import {
invalidArgumentMessage,
RequiredArgumentOptions,
validateMinNumberOfArguments,
validateOptional,
} from './validate';
import api = proto.google.firestore.v1;
/*!
* Error message for transactional reads that were executed after performing
* writes.
*/
const READ_AFTER_WRITE_ERROR_MSG =
'Firestore transactions require all reads to be executed before all writes.';
/*!
* Transactions can be retried if the initial stream opening errors out.
*/
const ALLOW_RETRIES = true;
/**
* A reference to a transaction.
*
* The Transaction object passed to a transaction's updateFunction provides
* the methods to read and write data within the transaction context. See
* [runTransaction()]{@link Firestore#runTransaction}.
*
* @class
*/
export class Transaction {
private _firestore: Firestore;
private _previousTransaction?: Transaction;
private _writeBatch: WriteBatch;
private _requestTag: string;
private _transactionId?: Uint8Array;
/**
* @private
* @hideconstructor
*
* @param firestore The Firestore Database client.
* @param previousTransaction If available, the failed transaction that is
* being retried.
*/
constructor(firestore: Firestore, previousTransaction?: Transaction) {
this._firestore = firestore;
this._previousTransaction = previousTransaction;
this._writeBatch = firestore.batch();
this._requestTag = previousTransaction
? previousTransaction.requestTag
: requestTag();
}
/**
* Retrieves a query result. Holds a pessimistic lock on all returned
* documents.
*
* @param {Query} query A query to execute.
* @return {Promise<QuerySnapshot>} A QuerySnapshot for the retrieved data.
*/
get(query: Query): Promise<QuerySnapshot>;
/**
* Reads the document referenced by the provided `DocumentReference.`
* Holds a pessimistic lock on the returned document.
*
* @param {DocumentReference} documentRef A reference to the document to be read.
* @return {Promise<DocumentSnapshot>} A DocumentSnapshot for the read data.
*/
get(documentRef: DocumentReference): Promise<DocumentSnapshot>;
/**
* Retrieve a document or a query result from the database. Holds a
* pessimistic lock on all returned documents.
*
* @param {DocumentReference|Query} refOrQuery The document or query to
* return.
* @returns {Promise} A Promise that resolves with a DocumentSnapshot or
* QuerySnapshot for the returned documents.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (doc.exists) {
* transaction.update(documentRef, { count: doc.get('count') + 1 });
* } else {
* transaction.create(documentRef, { count: 1 });
* }
* });
* });
*/
get(
refOrQuery: DocumentReference | Query
): Promise<DocumentSnapshot | QuerySnapshot> {
if (!this._writeBatch.isEmpty) {
throw new Error(READ_AFTER_WRITE_ERROR_MSG);
}
if (refOrQuery instanceof DocumentReference) {
return this._firestore
.getAll_(
[refOrQuery],
/* fieldMask= */ null,
this._requestTag,
this._transactionId
)
.then(res => {
return Promise.resolve(res[0]);
});
}
if (refOrQuery instanceof Query) {
return refOrQuery._get(this._transactionId);
}
throw new Error(
'Value for argument "refOrQuery" must be a DocumentReference or a Query.'
);
}
/**
* Retrieves multiple documents from Firestore. Holds a pessimistic lock on
* all returned documents.
*
* The first argument is required and must be of type `DocumentReference`
* followed by any additional `DocumentReference` documents. If used, the
* optional `ReadOptions` must be the last argument.
*
* @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The
* `DocumentReferences` to receive, followed by an optional field mask.
* @returns {Promise<Array.<DocumentSnapshot>>} A Promise that
* contains an array with the resulting document snapshots.
*
* @example
* let firstDoc = firestore.doc('col/doc1');
* let secondDoc = firestore.doc('col/doc2');
* let resultDoc = firestore.doc('col/doc3');
*
* firestore.runTransaction(transaction => {
* return transaction.getAll(firstDoc, secondDoc).then(docs => {
* transaction.set(resultDoc, {
* sum: docs[0].get('count') + docs[1].get('count')
* });
* });
* });
*/
getAll(
...documentRefsOrReadOptions: Array<DocumentReference | ReadOptions>
): Promise<DocumentSnapshot[]> {
if (!this._writeBatch.isEmpty) {
throw new Error(READ_AFTER_WRITE_ERROR_MSG);
}
validateMinNumberOfArguments('Transaction.getAll', arguments, 1);
const {documents, fieldMask} = parseGetAllArguments(
documentRefsOrReadOptions
);
return this._firestore.getAll_(
documents,
fieldMask,
this._requestTag,
this._transactionId
);
}
/**
* Create the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. The operation will
* fail the transaction if a document exists at the specified location.
*
* @param {DocumentReference} documentRef A reference to the document to be
* created.
* @param {DocumentData} data The object data to serialize as the document.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (!doc.exists) {
* transaction.create(documentRef, { foo: 'bar' });
* }
* });
* });
*/
create(documentRef: DocumentReference, data: DocumentData): Transaction {
this._writeBatch.create(documentRef, data);
return this;
}
/**
* Writes to the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document
* does not exist yet, it will be created. If you pass
* [SetOptions]{@link SetOptions}, the provided data can be merged into the
* existing document.
*
* @param {DocumentReference} documentRef A reference to the document to be
* set.
* @param {DocumentData} data The object to serialize as the document.
* @param {SetOptions=} options An object to configure the set behavior.
* @param {boolean=} options.merge - If true, set() merges the values
* specified in its data argument. Fields omitted from this set() call
* remain untouched.
* @param {Array.<string|FieldPath>=} options.mergeFields - If provided,
* set() only replaces the specified field paths. Any field path that is not
* specified is ignored and remains untouched.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* transaction.set(documentRef, { foo: 'bar' });
* return Promise.resolve();
* });
*/
set(
documentRef: DocumentReference,
data: DocumentData,
options?: SetOptions
): Transaction {
this._writeBatch.set(documentRef, data, options);
return this;
}
/**
* Updates fields in the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. The update will
* fail if applied to a document that does not exist.
*
* The update() method accepts either an object with field paths encoded as
* keys and field values encoded as values, or a variable number of arguments
* that alternate between field paths and field values. Nested fields can be
* updated by providing dot-separated field path strings or by providing
* FieldPath objects.
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {DocumentReference} documentRef A reference to the document to be
* updated.
* @param {UpdateData|string|FieldPath} dataOrField An object
* containing the fields and values with which to update the document
* or the path of the first field to update.
* @param {
* ...(Precondition|*|string|FieldPath)} preconditionOrValues -
* An alternating list of field paths and values to update or a Precondition
* to to enforce on this update.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (doc.exists) {
* transaction.update(documentRef, { count: doc.get('count') + 1 });
* } else {
* transaction.create(documentRef, { count: 1 });
* }
* });
* });
*/
update(
documentRef: DocumentReference,
dataOrField: UpdateData | string | FieldPath,
...preconditionOrValues: Array<Precondition | unknown | string | FieldPath>
): Transaction {
validateMinNumberOfArguments('Transaction.update', arguments, 2);
this._writeBatch.update.apply(this._writeBatch, [
documentRef,
dataOrField,
].concat(preconditionOrValues) as [DocumentReference, string]);
return this;
}
/**
* Deletes the document referred to by the provided [DocumentReference]
* {@link DocumentReference}.
*
* @param {DocumentReference} documentRef A reference to the document to be
* deleted.
* @param {Precondition=} precondition A precondition to enforce for this
* delete.
* @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
* document was last updated at lastUpdateTime. Fails the transaction if the
* document doesn't exist or was last updated at a different time.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* transaction.delete(documentRef);
* return Promise.resolve();
* });
*/
delete(
documentRef: DocumentReference,
precondition?: PublicPrecondition
): this {
this._writeBatch.delete(documentRef, precondition);
return this;
}
/**
* Starts a transaction and obtains the transaction id from the server.
*
* @private
*/
begin(): Promise<void> {
const request: api.IBeginTransactionRequest = {
database: this._firestore.formattedName,
};
if (this._previousTransaction) {
request.options = {
readWrite: {
retryTransaction: this._previousTransaction._transactionId,
},
};
}
return this._firestore
.request<api.IBeginTransactionResponse>(
'beginTransaction',
request,
this._requestTag,
ALLOW_RETRIES
)
.then(resp => {
this._transactionId = resp.transaction!;
});
}
/**
* Commits all queued-up changes in this transaction and releases all locks.
*
* @private
*/
commit(): Promise<void> {
return this._writeBatch
.commit_({
transactionId: this._transactionId,
requestTag: this._requestTag,
})
.then(() => {});
}
/**
* Releases all locks and rolls back this transaction.
*
* @private
*/
rollback(): Promise<void> {
const request = {
database: this._firestore.formattedName,
transaction: this._transactionId,
};
return this._firestore.request(
'rollback',
request,
this._requestTag,
/* allowRetries= */ false
);
}
/**
* Returns the tag to use with with all request for this Transaction.
* @private
* @return A unique client-generated identifier for this transaction.
*/
get requestTag(): string {
return this._requestTag;
}
}
/**
* Parses the arguments for the `getAll()` call supported by both the Firestore
* and Transaction class.
*
* @private
* @param documentRefsOrReadOptions An array of document references followed by
* an optional ReadOptions object.
*/
export function parseGetAllArguments(
documentRefsOrReadOptions: Array<DocumentReference | ReadOptions>
): {documents: DocumentReference[]; fieldMask: FieldPath[] | null} {
let documents: DocumentReference[];
let readOptions: ReadOptions | undefined = undefined;
if (Array.isArray(documentRefsOrReadOptions[0])) {
throw new Error(
'getAll() no longer accepts an array as its first argument. ' +
'Please unpack your array and call getAll() with individual arguments.'
);
}
if (
documentRefsOrReadOptions.length > 0 &&
isPlainObject(
documentRefsOrReadOptions[documentRefsOrReadOptions.length - 1]
)
) {
readOptions = documentRefsOrReadOptions.pop() as ReadOptions;
documents = documentRefsOrReadOptions as DocumentReference[];
} else {
documents = documentRefsOrReadOptions as DocumentReference[];
}
for (let i = 0; i < documents.length; ++i) {
validateDocumentReference(i, documents[i]);
}
validateReadOptions('options', readOptions, {optional: true});
const fieldMask =
readOptions && readOptions.fieldMask
? readOptions.fieldMask.map(fieldPath =>
FieldPath.fromArgument(fieldPath)
)
: null;
return {fieldMask, documents};
}
/**
* Validates the use of 'options' as ReadOptions and enforces that 'fieldMask'
* is an array of strings or field paths.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the ReadOptions can be omitted.
*/
function validateReadOptions(
arg: number | string,
value: unknown,
options?: RequiredArgumentOptions
): void {
if (!validateOptional(value, options)) {
if (!isObject(value)) {
throw new Error(
`${invalidArgumentMessage(arg, 'read option')} Input is not an object.'`
);
}
const options = value as {[k: string]: unknown};
if (options.fieldMask !== undefined) {
if (!Array.isArray(options.fieldMask)) {
throw new Error(
`${invalidArgumentMessage(
arg,
'read option'
)} "fieldMask" is not an array.`
);
}
for (let i = 0; i < options.fieldMask.length; ++i) {
try {
validateFieldPath(i, options.fieldMask[i]);
} catch (err) {
throw new Error(
`${invalidArgumentMessage(
arg,
'read option'
)} "fieldMask" is not valid: ${err.message}`
);
}
}
}
}
}