UNPKG

73.3 kBTypeScriptView Raw
1/*!
2 * Copyright 2020 Google LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// We deliberately use `any` in the external API to not impose type-checking
18// on end users.
19/* eslint-disable @typescript-eslint/no-explicit-any */
20
21// Declare a global (ambient) namespace
22// (used when not using import statement, but just script include).
23declare namespace FirebaseFirestore {
24 /**
25 * Document data (for use with `DocumentReference.set()`) consists of fields
26 * mapped to values.
27 */
28 export type DocumentData = {[field: string]: any};
29
30 /**
31 * Update data (for use with `DocumentReference.update()`) consists of field
32 * paths (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots
33 * reference nested fields within the document.
34 */
35 export type UpdateData = {[fieldPath: string]: any};
36
37 /**
38 * Sets or disables the log function for all active Firestore instances.
39 *
40 * @param logger A log function that takes a message (such as `console.log`) or
41 * `null` to turn off logging.
42 */
43 function setLogFunction(logger: ((msg: string) => void) | null): void;
44
45 /**
46 * Converter used by `withConverter()` to transform user objects of type T
47 * into Firestore data.
48 *
49 * Using the converter allows you to specify generic type arguments when
50 * storing and retrieving objects from Firestore.
51 *
52 * @example
53 * class Post {
54 * constructor(readonly title: string, readonly author: string) {}
55 *
56 * toString(): string {
57 * return this.title + ', by ' + this.author;
58 * }
59 * }
60 *
61 * const postConverter = {
62 * toFirestore(post: Post): FirebaseFirestore.DocumentData {
63 * return {title: post.title, author: post.author};
64 * },
65 * fromFirestore(
66 * snapshot: FirebaseFirestore.QueryDocumentSnapshot
67 * ): Post {
68 * const data = snapshot.data();
69 * return new Post(data.title, data.author);
70 * }
71 * };
72 *
73 * const postSnap = await Firestore()
74 * .collection('posts')
75 * .withConverter(postConverter)
76 * .doc().get();
77 * const post = postSnap.data();
78 * if (post !== undefined) {
79 * post.title; // string
80 * post.toString(); // Should be defined
81 * post.someNonExistentProperty; // TS error
82 * }
83 */
84 export interface FirestoreDataConverter<T> {
85 /**
86 * Called by the Firestore SDK to convert a custom model object of type T
87 * into a plain Javascript object (suitable for writing directly to the
88 * Firestore database). To use set() with `merge` and `mergeFields`,
89 * toFirestore() must be defined with `Partial<T>`.
90 */
91 toFirestore(modelObject: T): DocumentData;
92 toFirestore(modelObject: Partial<T>, options: SetOptions): DocumentData;
93
94 /**
95 * Called by the Firestore SDK to convert Firestore data into an object of
96 * type T.
97 */
98 fromFirestore(snapshot: QueryDocumentSnapshot): T;
99 }
100
101 /**
102 * Settings used to directly configure a `Firestore` instance.
103 */
104 export interface Settings {
105 /**
106 * The project ID from the Google Developer's Console, e.g.
107 * 'grape-spaceship-123'. We will also check the environment variable
108 * GCLOUD_PROJECT for your project ID. Can be omitted in environments that
109 * support {@link https://cloud.google.com/docs/authentication Application
110 * Default Credentials}
111 */
112 projectId?: string;
113
114 /** The hostname to connect to. */
115 host?: string;
116
117 /** The port to connect to. */
118 port?: number;
119
120 /**
121 * Local file containing the Service Account credentials as downloaded from
122 * the Google Developers Console. Can be omitted in environments that
123 * support {@link https://cloud.google.com/docs/authentication Application
124 * Default Credentials}. To configure Firestore with custom credentials, use
125 * the `credentials` property to provide the `client_email` and
126 * `private_key` of your service account.
127 */
128 keyFilename?: string;
129
130 /**
131 * The 'client_email' and 'private_key' properties of the service account
132 * to use with your Firestore project. Can be omitted in environments that
133 * support {@link https://cloud.google.com/docs/authentication Application
134 * Default Credentials}. If your credentials are stored in a JSON file, you
135 * can specify a `keyFilename` instead.
136 */
137 credentials?: {client_email?: string; private_key?: string};
138
139 /** Whether to use SSL when connecting. */
140 ssl?: boolean;
141
142 /**
143 * The maximum number of idle GRPC channels to keep. A smaller number of idle
144 * channels reduces memory usage but increases request latency for clients
145 * with fluctuating request rates. If set to 0, shuts down all GRPC channels
146 * when the client becomes idle. Defaults to 1.
147 */
148 maxIdleChannels?: number;
149
150 /**
151 * Whether to use `BigInt` for integer types when deserializing Firestore
152 * Documents. Regardless of magnitude, all integer values are returned as
153 * `BigInt` to match the precision of the Firestore backend. Floating point
154 * numbers continue to use JavaScript's `number` type.
155 */
156 useBigInt?: boolean;
157
158 /**
159 * Whether to skip nested properties that are set to `undefined` during
160 * object serialization. If set to `true`, these properties are skipped
161 * and not written to Firestore. If set `false` or omitted, the SDK throws
162 * an exception when it encounters properties of type `undefined`.
163 */
164 ignoreUndefinedProperties?: boolean;
165
166 [key: string]: any; // Accept other properties, such as GRPC settings.
167 }
168
169 /**
170 * `Firestore` represents a Firestore Database and is the entry point for all
171 * Firestore operations.
172 */
173 export class Firestore {
174 /**
175 * @param settings Configuration object. See [Firestore Documentation]
176 * {@link https://firebase.google.com/docs/firestore/}
177 */
178 public constructor(settings?: Settings);
179
180 /**
181 * Specifies custom settings to be used to configure the `Firestore`
182 * instance. Can only be invoked once and before any other Firestore
183 * method.
184 *
185 * If settings are provided via both `settings()` and the `Firestore`
186 * constructor, both settings objects are merged and any settings provided
187 * via `settings()` take precedence.
188 *
189 * @param {object} settings The settings to use for all Firestore
190 * operations.
191 */
192 settings(settings: Settings): void;
193
194 /**
195 * Gets a `CollectionReference` instance that refers to the collection at
196 * the specified path.
197 *
198 * @param collectionPath A slash-separated path to a collection.
199 * @return The `CollectionReference` instance.
200 */
201 collection(collectionPath: string): CollectionReference<DocumentData>;
202
203 /**
204 * Gets a `DocumentReference` instance that refers to the document at the
205 * specified path.
206 *
207 * @param documentPath A slash-separated path to a document.
208 * @return The `DocumentReference` instance.
209 */
210 doc(documentPath: string): DocumentReference<DocumentData>;
211
212 /**
213 * Creates and returns a new Query that includes all documents in the
214 * database that are contained in a collection or subcollection with the
215 * given collectionId.
216 *
217 * @param collectionId Identifies the collections to query over. Every
218 * collection or subcollection with this ID as the last segment of its path
219 * will be included. Cannot contain a slash.
220 * @return The created `CollectionGroup`.
221 */
222 collectionGroup(collectionId: string): CollectionGroup<DocumentData>;
223
224 /**
225 * Retrieves multiple documents from Firestore.
226 *
227 * The first argument is required and must be of type `DocumentReference`
228 * followed by any additional `DocumentReference` documents. If used, the
229 * optional `ReadOptions` must be the last argument.
230 *
231 * @param {Array.<DocumentReference|ReadOptions>} documentRefsOrReadOptions
232 * The `DocumentReferences` to receive, followed by an optional field
233 * mask.
234 * @return A Promise that resolves with an array of resulting document
235 * snapshots.
236 */
237 getAll(
238 ...documentRefsOrReadOptions: Array<
239 DocumentReference<DocumentData> | ReadOptions
240 >
241 ): Promise<Array<DocumentSnapshot<DocumentData>>>;
242
243 /**
244 * Terminates the Firestore client and closes all open streams.
245 *
246 * @return A Promise that resolves when the client is terminated.
247 */
248 terminate(): Promise<void>;
249
250 /**
251 * Fetches the root collections that are associated with this Firestore
252 * database.
253 *
254 * @returns A Promise that resolves with an array of CollectionReferences.
255 */
256 listCollections(): Promise<Array<CollectionReference<DocumentData>>>;
257
258 /**
259 * Executes the given updateFunction and commits the changes applied within
260 * the transaction.
261 *
262 * You can use the transaction object passed to 'updateFunction' to read and
263 * modify Firestore documents under lock. Transactions are committed once
264 * 'updateFunction' resolves and attempted up to five times on failure.
265 *
266 * @param updateFunction The function to execute within the transaction
267 * context.
268 * @param {object=} transactionOptions Transaction options.
269 * @param {number=} transactionOptions.maxAttempts The maximum number of
270 * attempts for this transaction.
271 * @return If the transaction completed successfully or was explicitly
272 * aborted (by the updateFunction returning a failed Promise), the Promise
273 * returned by the updateFunction will be returned here. Else if the
274 * transaction failed, a rejected Promise with the corresponding failure
275 * error will be returned.
276 */
277 runTransaction<T>(
278 updateFunction: (transaction: Transaction) => Promise<T>,
279 transactionOptions?: {maxAttempts?: number}
280 ): Promise<T>;
281
282 /**
283 * Creates a write batch, used for performing multiple writes as a single
284 * atomic operation.
285 */
286 batch(): WriteBatch;
287
288 /**
289 * Creates a [BulkWriter]{@link BulkWriter}, used for performing
290 * multiple writes in parallel. Gradually ramps up writes as specified
291 * by the 500/50/5 rule.
292 *
293 * @see https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic
294 *
295 * @param options An options object used to configure the throttling
296 * behavior for the underlying BulkWriter.
297 */
298 bulkWriter(options?: BulkWriterOptions): BulkWriter;
299
300 /**
301 * Creates a new `BundleBuilder` instance to package selected Firestore data into
302 * a bundle.
303 *
304 * @param bundleId The ID of the bundle. When loaded on clients, client SDKs use this ID
305 * and the timestamp associated with the bundle to tell if it has been loaded already.
306 * If not specified, a random identifier will be used.
307 *
308 *
309 * @example
310 * const bundle = firestore.bundle('data-bundle');
311 * const docSnapshot = await firestore.doc('abc/123').get();
312 * const querySnapshot = await firestore.collection('coll').get();
313 *
314 * const bundleBuffer = bundle.add(docSnapshot); // Add a document
315 * .add('coll-query', querySnapshot) // Add a named query.
316 * .build()
317 * // Save `bundleBuffer` to CDN or stream it to clients.
318 */
319 bundle(bundleId?: string): BundleBuilder;
320 }
321
322 /**
323 * An immutable object representing a geo point in Firestore. The geo point
324 * is represented as latitude/longitude pair.
325 *
326 * Latitude values are in the range of [-90, 90].
327 * Longitude values are in the range of [-180, 180].
328 */
329 export class GeoPoint {
330 /**
331 * Creates a new immutable GeoPoint object with the provided latitude and
332 * longitude values.
333 * @param latitude The latitude as number between -90 and 90.
334 * @param longitude The longitude as number between -180 and 180.
335 */
336 constructor(latitude: number, longitude: number);
337
338 readonly latitude: number;
339 readonly longitude: number;
340
341 /**
342 * Returns true if this `GeoPoint` is equal to the provided one.
343 *
344 * @param other The `GeoPoint` to compare against.
345 * @return true if this `GeoPoint` is equal to the provided one.
346 */
347 isEqual(other: GeoPoint): boolean;
348 }
349
350 /**
351 * A reference to a transaction.
352 * The `Transaction` object passed to a transaction's updateFunction provides
353 * the methods to read and write data within the transaction context. See
354 * `Firestore.runTransaction()`.
355 */
356 export class Transaction {
357 private constructor();
358
359 /**
360 * Retrieves a query result. Holds a pessimistic lock on all returned
361 * documents.
362 *
363 * @param query A query to execute.
364 * @return A QuerySnapshot for the retrieved data.
365 */
366 get<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
367
368 /**
369 * Reads the document referenced by the provided `DocumentReference.`
370 * Holds a pessimistic lock on the returned document.
371 *
372 * @param documentRef A reference to the document to be read.
373 * @return A DocumentSnapshot for the read data.
374 */
375 get<T>(documentRef: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
376
377 /**
378 * Retrieves multiple documents from Firestore. Holds a pessimistic lock on
379 * all returned documents.
380 *
381 * The first argument is required and must be of type `DocumentReference`
382 * followed by any additional `DocumentReference` documents. If used, the
383 * optional `ReadOptions` must be the last argument.
384 *
385 * @param {Array.<DocumentReference|ReadOptions>} documentRefsOrReadOptions
386 * The `DocumentReferences` to receive, followed by an optional field
387 * mask.
388 * @return A Promise that resolves with an array of resulting document
389 * snapshots.
390 */
391 getAll<T>(
392 ...documentRefsOrReadOptions: Array<DocumentReference<T> | ReadOptions>
393 ): Promise<Array<DocumentSnapshot<T>>>;
394
395 /**
396 * Create the document referred to by the provided `DocumentReference`.
397 * The operation will fail the transaction if a document exists at the
398 * specified location.
399 *
400 * @param documentRef A reference to the document to be create.
401 * @param data The object data to serialize as the document.
402 * @return This `Transaction` instance. Used for chaining method calls.
403 */
404 create<T>(documentRef: DocumentReference<T>, data: T): Transaction;
405
406 /**
407 * Writes to the document referred to by the provided `DocumentReference`.
408 * If the document does not exist yet, it will be created. If you pass
409 * `SetOptions`, the provided data can be merged into the existing document.
410 *
411 * @param documentRef A reference to the document to be set.
412 * @param data An object of the fields and values for the document.
413 * @param options An object to configure the set behavior.
414 * @return This `Transaction` instance. Used for chaining method calls.
415 */
416 set<T>(
417 documentRef: DocumentReference<T>,
418 data: Partial<T>,
419 options: SetOptions
420 ): Transaction;
421 set<T>(documentRef: DocumentReference<T>, data: T): Transaction;
422
423 /**
424 * Updates fields in the document referred to by the provided
425 * `DocumentReference`. The update will fail if applied to a document that
426 * does not exist.
427 *
428 * Nested fields can be updated by providing dot-separated field path
429 * strings.
430 *
431 * @param documentRef A reference to the document to be updated.
432 * @param data An object containing the fields and values with which to
433 * update the document.
434 * @param precondition A Precondition to enforce on this update.
435 * @return This `Transaction` instance. Used for chaining method calls.
436 */
437 update(
438 documentRef: DocumentReference<any>,
439 data: UpdateData,
440 precondition?: Precondition
441 ): Transaction;
442
443 /**
444 * Updates fields in the document referred to by the provided
445 * `DocumentReference`. The update will fail if applied to a document that
446 * does not exist.
447 *
448 * Nested fields can be updated by providing dot-separated field path
449 * strings or by providing FieldPath objects.
450 *
451 * A `Precondition` restricting this update can be specified as the last
452 * argument.
453 *
454 * @param documentRef A reference to the document to be updated.
455 * @param field The first field to update.
456 * @param value The first value
457 * @param fieldsOrPrecondition An alternating list of field paths and values
458 * to update, optionally followed by a `Precondition` to enforce on this
459 * update.
460 * @return This `Transaction` instance. Used for chaining method calls.
461 */
462 update(
463 documentRef: DocumentReference<any>,
464 field: string | FieldPath,
465 value: any,
466 ...fieldsOrPrecondition: any[]
467 ): Transaction;
468
469 /**
470 * Deletes the document referred to by the provided `DocumentReference`.
471 *
472 * @param documentRef A reference to the document to be deleted.
473 * @param precondition A Precondition to enforce for this delete.
474 * @return This `Transaction` instance. Used for chaining method calls.
475 */
476 delete(
477 documentRef: DocumentReference<any>,
478 precondition?: Precondition
479 ): Transaction;
480 }
481
482 /**
483 * A Firestore BulkWriter than can be used to perform a large number of writes
484 * in parallel. Writes to the same document will be executed sequentially.
485 *
486 * @class
487 */
488 export class BulkWriter {
489 private constructor();
490
491 /**
492 * Create a document with the provided data. This single operation will fail
493 * if a document exists at its location.
494 *
495 * @param documentRef A reference to the document to be
496 * created.
497 * @param data The object to serialize as the document.
498 * @returns A promise that resolves with the result of the write. If the
499 * write fails, the promise is rejected with a
500 * [BulkWriterError]{@link BulkWriterError}.
501 */
502 create<T>(documentRef: DocumentReference<T>, data: T): Promise<WriteResult>;
503
504 /**
505 * Delete a document from the database.
506 *
507 * @param documentRef A reference to the document to be
508 * deleted.
509 * @param precondition A precondition to enforce for this
510 * delete.
511 * @param precondition.lastUpdateTime If set, enforces that the
512 * document was last updated at lastUpdateTime. Fails the batch if the
513 * document doesn't exist or was last updated at a different time.
514 * @returns A promise that resolves with the result of the delete. If the
515 * delete fails, the promise is rejected with a
516 * [BulkWriterError]{@link BulkWriterError}.
517 */
518 delete(
519 documentRef: DocumentReference<any>,
520 precondition?: Precondition
521 ): Promise<WriteResult>;
522
523 /**
524 * Write to the document referred to by the provided
525 * [DocumentReference]{@link DocumentReference}. If the document does not
526 * exist yet, it will be created. If you pass
527 * [SetOptions]{@link SetOptions}., the provided data can be merged into the
528 * existing document.
529 *
530 * @param documentRef A reference to the document to be
531 * set.
532 * @param data The object to serialize as the document.
533 * @param options An object to configure the set behavior.
534 * @param options.merge - If true, set() merges the values
535 * specified in its data argument. Fields omitted from this set() call
536 * remain untouched.
537 * @param options.mergeFields - If provided,
538 * set() only replaces the specified field paths. Any field path that is not
539 * specified is ignored and remains untouched.
540 * @returns A promise that resolves with the result of the write. If the
541 * write fails, the promise is rejected with a
542 * [BulkWriterError]{@link BulkWriterError}.
543 */
544 set<T>(
545 documentRef: DocumentReference<T>,
546 data: Partial<T>,
547 options: SetOptions
548 ): Promise<WriteResult>;
549 set<T>(documentRef: DocumentReference<T>, data: T): Promise<WriteResult>;
550
551 /**
552 * Update fields of the document referred to by the provided
553 * [DocumentReference]{@link DocumentReference}. If the document doesn't yet
554 * exist, the update fails and the entire batch will be rejected.
555 *
556 * The update() method accepts either an object with field paths encoded as
557 * keys and field values encoded as values, or a variable number of
558 * arguments that alternate between field paths and field values. Nested
559 * fields can be updated by providing dot-separated field path strings or by
560 * providing FieldPath objects.
561 *
562 *
563 * A Precondition restricting this update can be specified as the last
564 * argument.
565 *
566 * @param documentRef A reference to the document to be updated.
567 * @param data An object containing the fields and values with which to
568 * update the document.
569 * @param precondition A Precondition to enforce on this update.
570 * @returns A promise that resolves with the result of the write. If the
571 * write fails, the promise is rejected with a
572 * [BulkWriterError]{@link BulkWriterError}.
573 */
574 update(
575 documentRef: DocumentReference<any>,
576 data: UpdateData,
577 precondition?: Precondition
578 ): Promise<WriteResult>;
579
580 /**
581 * Update fields of the document referred to by the provided
582 * [DocumentReference]{@link DocumentReference}. If the document doesn't yet
583 * exist, the update fails and the entire batch will be rejected.
584 *
585 * The update() method accepts either an object with field paths encoded as
586 * keys and field values encoded as values, or a variable number of
587 * arguments that alternate between field paths and field values. Nested
588 * fields can be updated by providing dot-separated field path strings or by
589 * providing FieldPath objects.
590 *
591 *
592 * A Precondition restricting this update can be specified as the last
593 * argument.
594 *
595 * @param documentRef A reference to the document to be updated.
596 * @param field The first field to update.
597 * @param value The first value
598 * @param fieldsOrPrecondition An alternating list of field paths and values
599 * to update, optionally followed a `Precondition` to enforce on this update.
600 * @returns A promise that resolves with the result of the write. If the
601 * write fails, the promise is rejected with a
602 * [BulkWriterError]{@link BulkWriterError}.
603 */
604 update(
605 documentRef: DocumentReference<any>,
606 field: string | FieldPath,
607 value: any,
608 ...fieldsOrPrecondition: any[]
609 ): Promise<WriteResult>;
610
611 /**
612 * Attaches a listener that is run every time a BulkWriter operation
613 * successfully completes.
614 *
615 * @param callback A callback to be called every time a BulkWriter operation
616 * successfully completes.
617 */
618 onWriteResult(
619 callback: (
620 documentRef: DocumentReference<any>,
621 result: WriteResult
622 ) => void
623 ): void;
624
625 /**
626 * Attaches an error handler listener that is run every time a BulkWriter
627 * operation fails.
628 *
629 * BulkWriter has a default error handler that retries UNAVAILABLE and
630 * ABORTED errors up to a maximum of 10 failed attempts. When an error
631 * handler is specified, the default error handler will be overwritten.
632 *
633 * @param shouldRetryCallback A callback to be called every time a BulkWriter
634 * operation fails. Returning `true` will retry the operation. Returning
635 * `false` will stop the retry loop.
636 */
637 onWriteError(
638 shouldRetryCallback: (error: BulkWriterError) => boolean
639 ): void;
640
641 /**
642 * Commits all writes that have been enqueued up to this point in parallel.
643 *
644 * Returns a Promise that resolves when all currently queued operations have
645 * been committed. The Promise will never be rejected since the results for
646 * each individual operation are conveyed via their individual Promises.
647 *
648 * The Promise resolves immediately if there are no pending writes.
649 * Otherwise, the Promise waits for all previously issued writes, but it
650 * does not wait for writes that were added after the method is called. If
651 * you want to wait for additional writes, call `flush()` again.
652 *
653 * @return A promise that resolves when all enqueued writes
654 * up to this point have been committed.
655 */
656 flush(): Promise<void>;
657
658 /**
659 * Commits all enqueued writes and marks the BulkWriter instance as closed.
660 *
661 * After calling `close()`, calling any method will throw an error. Any
662 * retries scheduled as part of an `onWriteError()` handler will be run
663 * before the `close()` promise resolves.
664 *
665 * Returns a Promise that resolves when all writes have been committed. The
666 * Promise will never be rejected. Calling this method will send all
667 * requests. The promise resolves immediately if there are no pending
668 * writes.
669 *
670 * @return A promise that resolves when all enqueued writes
671 * up to this point have been committed.
672 */
673 close(): Promise<void>;
674 }
675
676 /**
677 * An options object to configure throttling on BulkWriter.
678 */
679 export interface BulkWriterOptions {
680 /**
681 * Whether to disable or configure throttling. By default, throttling is
682 * enabled. This field can be set to either a boolean or a config
683 * object. Setting it to `true` will use default values. You can override
684 * the defaults by setting it to `false` to disable throttling, or by
685 * setting the config values to enable throttling with the provided values.
686 *
687 * @see https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic
688 *
689 * @param initialOpsPerSecond The initial maximum number of operations per
690 * second allowed by the throttler. If this field is not set, the default
691 * is 500 operations per second.
692 * @param maxOpsPerSecond The maximum number of operations per second
693 * allowed by the throttler. If this field is set, the throttler's allowed
694 * operations per second does not ramp up past the specified operations per
695 * second.
696 */
697 readonly throttling?:
698 | boolean
699 | {initialOpsPerSecond?: number; maxOpsPerSecond?: number};
700 }
701
702 /**
703 * The error thrown when a BulkWriter operation fails.
704 */
705 export class BulkWriterError extends Error {
706 /** The status code of the error. */
707 readonly code: GrpcStatus;
708
709 /** The error message of the error. */
710 readonly message: string;
711
712 /** The document reference the operation was performed on. */
713 readonly documentRef: DocumentReference<any>;
714
715 /** The type of operation performed. */
716 readonly operationType: 'create' | 'set' | 'update' | 'delete';
717
718 /** How many times this operation has been attempted unsuccessfully. */
719 readonly failedAttempts: number;
720 }
721
722 /**
723 * A write batch, used to perform multiple writes as a single atomic unit.
724 *
725 * A `WriteBatch` object can be acquired by calling `Firestore.batch()`. It
726 * provides methods for adding writes to the write batch. None of the
727 * writes will be committed (or visible locally) until `WriteBatch.commit()`
728 * is called.
729 *
730 * Unlike transactions, write batches are persisted offline and therefore are
731 * preferable when you don't need to condition your writes on read data.
732 */
733 export class WriteBatch {
734 private constructor();
735
736 /**
737 * Create the document referred to by the provided `DocumentReference`. The
738 * operation will fail the batch if a document exists at the specified
739 * location.
740 *
741 * @param documentRef A reference to the document to be created.
742 * @param data The object data to serialize as the document.
743 * @return This `WriteBatch` instance. Used for chaining method calls.
744 */
745 create<T>(documentRef: DocumentReference<T>, data: T): WriteBatch;
746
747 /**
748 * Write to the document referred to by the provided `DocumentReference`.
749 * If the document does not exist yet, it will be created. If you pass
750 * `SetOptions`, the provided data can be merged into the existing document.
751 *
752 * @param documentRef A reference to the document to be set.
753 * @param data An object of the fields and values for the document.
754 * @param options An object to configure the set behavior.
755 * @return This `WriteBatch` instance. Used for chaining method calls.
756 */
757 set<T>(
758 documentRef: DocumentReference<T>,
759 data: Partial<T>,
760 options: SetOptions
761 ): WriteBatch;
762 set<T>(documentRef: DocumentReference<T>, data: T): WriteBatch;
763
764 /**
765 * Update fields of the document referred to by the provided
766 * `DocumentReference`. If the document doesn't yet exist, the update fails
767 * and the entire batch will be rejected.
768 *
769 * Nested fields can be updated by providing dot-separated field path
770 * strings.
771 *
772 * @param documentRef A reference to the document to be updated.
773 * @param data An object containing the fields and values with which to
774 * update the document.
775 * @param precondition A Precondition to enforce on this update.
776 * @return This `WriteBatch` instance. Used for chaining method calls.
777 */
778 update(
779 documentRef: DocumentReference<any>,
780 data: UpdateData,
781 precondition?: Precondition
782 ): WriteBatch;
783
784 /**
785 * Updates fields in the document referred to by the provided
786 * `DocumentReference`. The update will fail if applied to a document that
787 * does not exist.
788 *
789 * Nested fields can be updated by providing dot-separated field path
790 * strings or by providing FieldPath objects.
791 *
792 * A `Precondition` restricting this update can be specified as the last
793 * argument.
794 *
795 * @param documentRef A reference to the document to be updated.
796 * @param field The first field to update.
797 * @param value The first value
798 * @param fieldsOrPrecondition An alternating list of field paths and values
799 * to update, optionally followed a `Precondition` to enforce on this update.
800 * @return This `WriteBatch` instance. Used for chaining method calls.
801 */
802 update(
803 documentRef: DocumentReference<any>,
804 field: string | FieldPath,
805 value: any,
806 ...fieldsOrPrecondition: any[]
807 ): WriteBatch;
808
809 /**
810 * Deletes the document referred to by the provided `DocumentReference`.
811 *
812 * @param documentRef A reference to the document to be deleted.
813 * @param precondition A Precondition to enforce for this delete.
814 * @return This `WriteBatch` instance. Used for chaining method calls.
815 */
816 delete(
817 documentRef: DocumentReference<any>,
818 precondition?: Precondition
819 ): WriteBatch;
820
821 /**
822 * Commits all of the writes in this write batch as a single atomic unit.
823 *
824 * @return A Promise resolved once all of the writes in the batch have been
825 * successfully written to the backend as an atomic unit.
826 */
827 commit(): Promise<WriteResult[]>;
828 }
829
830 /**
831 * An options object that configures conditional behavior of `update()` and
832 * `delete()` calls in `DocumentReference`, `WriteBatch`, and `Transaction`.
833 * Using Preconditions, these calls can be restricted to only apply to
834 * documents that match the specified restrictions.
835 */
836 export interface Precondition {
837 /**
838 * If set, the last update time to enforce.
839 */
840 readonly lastUpdateTime?: Timestamp;
841 }
842
843 /**
844 * An options object that configures the behavior of `set()` calls in
845 * `DocumentReference`, `WriteBatch` and `Transaction`. These calls can be
846 * configured to perform granular merges instead of overwriting the target
847 * documents in their entirety.
848 */
849 export interface SetOptions {
850 /**
851 * Changes the behavior of a set() call to only replace the values specified
852 * in its data argument. Fields omitted from the set() call remain
853 * untouched.
854 */
855 readonly merge?: boolean;
856
857 /**
858 * Changes the behavior of set() calls to only replace the specified field
859 * paths. Any field path that is not specified is ignored and remains
860 * untouched.
861 *
862 * It is an error to pass a SetOptions object to a set() call that is
863 * missing a value for any of the fields specified here.
864 */
865 readonly mergeFields?: (string | FieldPath)[];
866 }
867
868 /**
869 * An options object that can be used to configure the behavior of `getAll()`
870 * calls. By providing a `fieldMask`, these calls can be configured to only
871 * return a subset of fields.
872 */
873 export interface ReadOptions {
874 /**
875 * Specifies the set of fields to return and reduces the amount of data
876 * transmitted by the backend.
877 *
878 * Adding a field mask does not filter results. Documents do not need to
879 * contain values for all the fields in the mask to be part of the result
880 * set.
881 */
882 readonly fieldMask?: (string | FieldPath)[];
883 }
884
885 /**
886 * A WriteResult wraps the write time set by the Firestore servers on `sets()`,
887 * `updates()`, and `creates()`.
888 */
889 export class WriteResult {
890 private constructor();
891
892 /**
893 * The write time as set by the Firestore servers.
894 */
895 readonly writeTime: Timestamp;
896
897 /**
898 * Returns true if this `WriteResult` is equal to the provided one.
899 *
900 * @param other The `WriteResult` to compare against.
901 * @return true if this `WriteResult` is equal to the provided one.
902 */
903 isEqual(other: WriteResult): boolean;
904 }
905
906 /**
907 * A `DocumentReference` refers to a document location in a Firestore database
908 * and can be used to write, read, or listen to the location. The document at
909 * the referenced location may or may not exist. A `DocumentReference` can
910 * also be used to create a `CollectionReference` to a subcollection.
911 */
912 export class DocumentReference<T = DocumentData> {
913 private constructor();
914
915 /** The identifier of the document within its collection. */
916 readonly id: string;
917
918 /**
919 * The `Firestore` for the Firestore database (useful for performing
920 * transactions, etc.).
921 */
922 readonly firestore: Firestore;
923
924 /**
925 * A reference to the Collection to which this DocumentReference belongs.
926 */
927 readonly parent: CollectionReference<T>;
928
929 /**
930 * A string representing the path of the referenced document (relative
931 * to the root of the database).
932 */
933 readonly path: string;
934
935 /**
936 * Gets a `CollectionReference` instance that refers to the collection at
937 * the specified path.
938 *
939 * @param collectionPath A slash-separated path to a collection.
940 * @return The `CollectionReference` instance.
941 */
942 collection(collectionPath: string): CollectionReference<DocumentData>;
943
944 /**
945 * Fetches the subcollections that are direct children of this document.
946 *
947 * @returns A Promise that resolves with an array of CollectionReferences.
948 */
949 listCollections(): Promise<Array<CollectionReference<DocumentData>>>;
950
951 /**
952 * Creates a document referred to by this `DocumentReference` with the
953 * provided object values. The write fails if the document already exists
954 *
955 * @param data The object data to serialize as the document.
956 * @return A Promise resolved with the write time of this create.
957 */
958 create(data: T): Promise<WriteResult>;
959
960 /**
961 * Writes to the document referred to by this `DocumentReference`. If the
962 * document does not yet exist, it will be created. If you pass
963 * `SetOptions`, the provided data can be merged into an existing document.
964 *
965 * @param data A map of the fields and values for the document.
966 * @param options An object to configure the set behavior.
967 * @return A Promise resolved with the write time of this set.
968 */
969 set(data: Partial<T>, options: SetOptions): Promise<WriteResult>;
970 set(data: T): Promise<WriteResult>;
971
972 /**
973 * Updates fields in the document referred to by this `DocumentReference`.
974 * The update will fail if applied to a document that does not exist.
975 *
976 * Nested fields can be updated by providing dot-separated field path
977 * strings.
978 *
979 * @param data An object containing the fields and values with which to
980 * update the document.
981 * @param precondition A Precondition to enforce on this update.
982 * @return A Promise resolved with the write time of this update.
983 */
984 update(data: UpdateData, precondition?: Precondition): Promise<WriteResult>;
985
986 /**
987 * Updates fields in the document referred to by this `DocumentReference`.
988 * The update will fail if applied to a document that does not exist.
989 *
990 * Nested fields can be updated by providing dot-separated field path
991 * strings or by providing FieldPath objects.
992 *
993 * A `Precondition` restricting this update can be specified as the last
994 * argument.
995 *
996 * @param field The first field to update.
997 * @param value The first value.
998 * @param moreFieldsOrPrecondition An alternating list of field paths and
999 * values to update, optionally followed by a `Precondition` to enforce on
1000 * this update.
1001 * @return A Promise resolved with the write time of this update.
1002 */
1003 update(
1004 field: string | FieldPath,
1005 value: any,
1006 ...moreFieldsOrPrecondition: any[]
1007 ): Promise<WriteResult>;
1008
1009 /**
1010 * Deletes the document referred to by this `DocumentReference`.
1011 *
1012 * @param precondition A Precondition to enforce for this delete.
1013 * @return A Promise resolved with the write time of this delete.
1014 */
1015 delete(precondition?: Precondition): Promise<WriteResult>;
1016
1017 /**
1018 * Reads the document referred to by this `DocumentReference`.
1019 *
1020 * @return A Promise resolved with a DocumentSnapshot containing the
1021 * current document contents.
1022 */
1023 get(): Promise<DocumentSnapshot<T>>;
1024
1025 /**
1026 * Attaches a listener for DocumentSnapshot events.
1027 *
1028 * @param onNext A callback to be called every time a new `DocumentSnapshot`
1029 * is available.
1030 * @param onError A callback to be called if the listen fails or is
1031 * cancelled. No further callbacks will occur.
1032 * @return An unsubscribe function that can be called to cancel
1033 * the snapshot listener.
1034 */
1035 onSnapshot(
1036 onNext: (snapshot: DocumentSnapshot<T>) => void,
1037 onError?: (error: Error) => void
1038 ): () => void;
1039
1040 /**
1041 * Returns true if this `DocumentReference` is equal to the provided one.
1042 *
1043 * @param other The `DocumentReference` to compare against.
1044 * @return true if this `DocumentReference` is equal to the provided one.
1045 */
1046 isEqual(other: DocumentReference<T>): boolean;
1047
1048 /**
1049 * Applies a custom data converter to this DocumentReference, allowing you
1050 * to use your own custom model objects with Firestore. When you call
1051 * set(), get(), etc. on the returned DocumentReference instance, the
1052 * provided converter will convert between Firestore data and your custom
1053 * type U.
1054 *
1055 * @param converter Converts objects to and from Firestore. Passing in
1056 * `null` removes the current converter.
1057 * @return A DocumentReference<U> that uses the provided converter.
1058 */
1059 withConverter<U>(
1060 converter: FirestoreDataConverter<U>
1061 ): DocumentReference<U>;
1062 withConverter(converter: null): DocumentReference<DocumentData>;
1063 }
1064
1065 /**
1066 * A `DocumentSnapshot` contains data read from a document in your Firestore
1067 * database. The data can be extracted with `.data()` or `.get(<field>)` to
1068 * get a specific field.
1069 *
1070 * For a `DocumentSnapshot` that points to a non-existing document, any data
1071 * access will return 'undefined'. You can use the `exists` property to
1072 * explicitly verify a document's existence.
1073 */
1074 export class DocumentSnapshot<T = DocumentData> {
1075 protected constructor();
1076
1077 /** True if the document exists. */
1078 readonly exists: boolean;
1079
1080 /** A `DocumentReference` to the document location. */
1081 readonly ref: DocumentReference<T>;
1082
1083 /**
1084 * The ID of the document for which this `DocumentSnapshot` contains data.
1085 */
1086 readonly id: string;
1087
1088 /**
1089 * The time the document was created. Not set for documents that don't
1090 * exist.
1091 */
1092 readonly createTime?: Timestamp;
1093
1094 /**
1095 * The time the document was last updated (at the time the snapshot was
1096 * generated). Not set for documents that don't exist.
1097 */
1098 readonly updateTime?: Timestamp;
1099
1100 /**
1101 * The time this snapshot was read.
1102 */
1103 readonly readTime: Timestamp;
1104
1105 /**
1106 * Retrieves all fields in the document as an Object. Returns 'undefined' if
1107 * the document doesn't exist.
1108 *
1109 * @return An Object containing all fields in the document.
1110 */
1111 data(): T | undefined;
1112
1113 /**
1114 * Retrieves the field specified by `fieldPath`.
1115 *
1116 * @param fieldPath The path (e.g. 'foo' or 'foo.bar') to a specific field.
1117 * @return The data at the specified field location or undefined if no such
1118 * field exists in the document.
1119 */
1120 get(fieldPath: string | FieldPath): any;
1121
1122 /**
1123 * Returns true if the document's data and path in this `DocumentSnapshot`
1124 * is equal to the provided one.
1125 *
1126 * @param other The `DocumentSnapshot` to compare against.
1127 * @return true if this `DocumentSnapshot` is equal to the provided one.
1128 */
1129 isEqual(other: DocumentSnapshot<T>): boolean;
1130 }
1131
1132 /**
1133 * A `QueryDocumentSnapshot` contains data read from a document in your
1134 * Firestore database as part of a query. The document is guaranteed to exist
1135 * and its data can be extracted with `.data()` or `.get(<field>)` to get a
1136 * specific field.
1137 *
1138 * A `QueryDocumentSnapshot` offers the same API surface as a
1139 * `DocumentSnapshot`. Since query results contain only existing documents, the
1140 * `exists` property will always be true and `data()` will never return
1141 * 'undefined'.
1142 */
1143 export class QueryDocumentSnapshot<
1144 T = DocumentData
1145 > extends DocumentSnapshot<T> {
1146 private constructor();
1147
1148 /**
1149 * The time the document was created.
1150 */
1151 readonly createTime: Timestamp;
1152
1153 /**
1154 * The time the document was last updated (at the time the snapshot was
1155 * generated).
1156 */
1157 readonly updateTime: Timestamp;
1158
1159 /**
1160 * Retrieves all fields in the document as an Object.
1161 *
1162 * @override
1163 * @return An Object containing all fields in the document.
1164 */
1165 data(): T;
1166 }
1167
1168 /**
1169 * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc'
1170 * (descending or ascending).
1171 */
1172 export type OrderByDirection = 'desc' | 'asc';
1173
1174 /**
1175 * Filter conditions in a `Query.where()` clause are specified using the
1176 * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', 'not-in',
1177 * and 'array-contains-any'.
1178 */
1179 export type WhereFilterOp =
1180 | '<'
1181 | '<='
1182 | '=='
1183 | '!='
1184 | '>='
1185 | '>'
1186 | 'array-contains'
1187 | 'in'
1188 | 'not-in'
1189 | 'array-contains-any';
1190
1191 /**
1192 * A `Query` refers to a Query which you can read or listen to. You can also
1193 * construct refined `Query` objects by adding filters and ordering.
1194 */
1195 export class Query<T = DocumentData> {
1196 protected constructor();
1197
1198 /**
1199 * The `Firestore` for the Firestore database (useful for performing
1200 * transactions, etc.).
1201 */
1202 readonly firestore: Firestore;
1203
1204 /**
1205 * Creates and returns a new Query with the additional filter that documents
1206 * must contain the specified field and that its value should satisfy the
1207 * relation constraint provided.
1208 *
1209 * This function returns a new (immutable) instance of the Query (rather
1210 * than modify the existing instance) to impose the filter.
1211 *
1212 * @param fieldPath The path to compare
1213 * @param opStr The operation string (e.g "<", "<=", "==", ">", ">=").
1214 * @param value The value for comparison
1215 * @return The created Query.
1216 */
1217 where(
1218 fieldPath: string | FieldPath,
1219 opStr: WhereFilterOp,
1220 value: any
1221 ): Query<T>;
1222
1223 /**
1224 * Creates and returns a new Query that's additionally sorted by the
1225 * specified field, optionally in descending order instead of ascending.
1226 *
1227 * This function returns a new (immutable) instance of the Query (rather
1228 * than modify the existing instance) to impose the order.
1229 *
1230 * @param fieldPath The field to sort by.
1231 * @param directionStr Optional direction to sort by ('asc' or 'desc'). If
1232 * not specified, order will be ascending.
1233 * @return The created Query.
1234 */
1235 orderBy(
1236 fieldPath: string | FieldPath,
1237 directionStr?: OrderByDirection
1238 ): Query<T>;
1239
1240 /**
1241 * Creates and returns a new Query that only returns the first matching
1242 * documents.
1243 *
1244 * This function returns a new (immutable) instance of the Query (rather
1245 * than modify the existing instance) to impose the limit.
1246 *
1247 * @param limit The maximum number of items to return.
1248 * @return The created Query.
1249 */
1250 limit(limit: number): Query<T>;
1251
1252 /**
1253 * Creates and returns a new Query that only returns the last matching
1254 * documents.
1255 *
1256 * You must specify at least one orderBy clause for limitToLast queries,
1257 * otherwise an exception will be thrown during execution.
1258 *
1259 * Results for limitToLast queries cannot be streamed via the `stream()`
1260 * API.
1261 *
1262 * @param limit The maximum number of items to return.
1263 * @return The created Query.
1264 */
1265 limitToLast(limit: number): Query<T>;
1266
1267 /**
1268 * Specifies the offset of the returned results.
1269 *
1270 * This function returns a new (immutable) instance of the Query (rather
1271 * than modify the existing instance) to impose the offset.
1272 *
1273 * @param offset The offset to apply to the Query results.
1274 * @return The created Query.
1275 */
1276 offset(offset: number): Query<T>;
1277
1278 /**
1279 * Creates and returns a new Query instance that applies a field mask to
1280 * the result and returns only the specified subset of fields. You can
1281 * specify a list of field paths to return, or use an empty list to only
1282 * return the references of matching documents.
1283 *
1284 * Queries that contain field masks cannot be listened to via `onSnapshot()`
1285 * listeners.
1286 *
1287 * This function returns a new (immutable) instance of the Query (rather
1288 * than modify the existing instance) to impose the field mask.
1289 *
1290 * @param field The field paths to return.
1291 * @return The created Query.
1292 */
1293 select(...field: (string | FieldPath)[]): Query<DocumentData>;
1294
1295 /**
1296 * Creates and returns a new Query that starts at the provided document
1297 * (inclusive). The starting position is relative to the order of the query.
1298 * The document must contain all of the fields provided in the orderBy of
1299 * this query.
1300 *
1301 * @param snapshot The snapshot of the document to start after.
1302 * @return The created Query.
1303 */
1304 startAt(snapshot: DocumentSnapshot<any>): Query<T>;
1305
1306 /**
1307 * Creates and returns a new Query that starts at the provided fields
1308 * relative to the order of the query. The order of the field values
1309 * must match the order of the order by clauses of the query.
1310 *
1311 * @param fieldValues The field values to start this query at, in order
1312 * of the query's order by.
1313 * @return The created Query.
1314 */
1315 startAt(...fieldValues: any[]): Query<T>;
1316
1317 /**
1318 * Creates and returns a new Query that starts after the provided document
1319 * (exclusive). The starting position is relative to the order of the query.
1320 * The document must contain all of the fields provided in the orderBy of
1321 * this query.
1322 *
1323 * @param snapshot The snapshot of the document to start after.
1324 * @return The created Query.
1325 */
1326 startAfter(snapshot: DocumentSnapshot<any>): Query<T>;
1327
1328 /**
1329 * Creates and returns a new Query that starts after the provided fields
1330 * relative to the order of the query. The order of the field values
1331 * must match the order of the order by clauses of the query.
1332 *
1333 * @param fieldValues The field values to start this query after, in order
1334 * of the query's order by.
1335 * @return The created Query.
1336 */
1337 startAfter(...fieldValues: any[]): Query<T>;
1338
1339 /**
1340 * Creates and returns a new Query that ends before the provided document
1341 * (exclusive). The end position is relative to the order of the query. The
1342 * document must contain all of the fields provided in the orderBy of this
1343 * query.
1344 *
1345 * @param snapshot The snapshot of the document to end before.
1346 * @return The created Query.
1347 */
1348 endBefore(snapshot: DocumentSnapshot<any>): Query<T>;
1349
1350 /**
1351 * Creates and returns a new Query that ends before the provided fields
1352 * relative to the order of the query. The order of the field values
1353 * must match the order of the order by clauses of the query.
1354 *
1355 * @param fieldValues The field values to end this query before, in order
1356 * of the query's order by.
1357 * @return The created Query.
1358 */
1359 endBefore(...fieldValues: any[]): Query<T>;
1360
1361 /**
1362 * Creates and returns a new Query that ends at the provided document
1363 * (inclusive). The end position is relative to the order of the query. The
1364 * document must contain all of the fields provided in the orderBy of this
1365 * query.
1366 *
1367 * @param snapshot The snapshot of the document to end at.
1368 * @return The created Query.
1369 */
1370 endAt(snapshot: DocumentSnapshot<any>): Query<T>;
1371
1372 /**
1373 * Creates and returns a new Query that ends at the provided fields
1374 * relative to the order of the query. The order of the field values
1375 * must match the order of the order by clauses of the query.
1376 *
1377 * @param fieldValues The field values to end this query at, in order
1378 * of the query's order by.
1379 * @return The created Query.
1380 */
1381 endAt(...fieldValues: any[]): Query<T>;
1382
1383 /**
1384 * Executes the query and returns the results as a `QuerySnapshot`.
1385 *
1386 * @return A Promise that will be resolved with the results of the Query.
1387 */
1388 get(): Promise<QuerySnapshot<T>>;
1389
1390 /*
1391 * Executes the query and returns the results as Node Stream.
1392 *
1393 * @return A stream of QueryDocumentSnapshot.
1394 */
1395 stream(): NodeJS.ReadableStream;
1396
1397 /**
1398 * Attaches a listener for `QuerySnapshot `events.
1399 *
1400 * @param onNext A callback to be called every time a new `QuerySnapshot`
1401 * is available.
1402 * @param onError A callback to be called if the listen fails or is
1403 * cancelled. No further callbacks will occur.
1404 * @return An unsubscribe function that can be called to cancel
1405 * the snapshot listener.
1406 */
1407 onSnapshot(
1408 onNext: (snapshot: QuerySnapshot<T>) => void,
1409 onError?: (error: Error) => void
1410 ): () => void;
1411
1412 /**
1413 * Returns true if this `Query` is equal to the provided one.
1414 *
1415 * @param other The `Query` to compare against.
1416 * @return true if this `Query` is equal to the provided one.
1417 */
1418 isEqual(other: Query<T>): boolean;
1419
1420 /**
1421 * Applies a custom data converter to this Query, allowing you to use your
1422 * own custom model objects with Firestore. When you call get() on the
1423 * returned Query, the provided converter will convert between Firestore
1424 * data and your custom type U.
1425 *
1426 * @param converter Converts objects to and from Firestore. Passing in
1427 * `null` removes the current converter.
1428 * @return A Query<U> that uses the provided converter.
1429 */
1430 withConverter<U>(converter: FirestoreDataConverter<U>): Query<U>;
1431 withConverter(converter: null): Query<DocumentData>;
1432 }
1433
1434 /**
1435 * A `QuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects
1436 * representing the results of a query. The documents can be accessed as an
1437 * array via the `docs` property or enumerated using the `forEach` method. The
1438 * number of documents can be determined via the `empty` and `size`
1439 * properties.
1440 */
1441 export class QuerySnapshot<T = DocumentData> {
1442 private constructor();
1443
1444 /**
1445 * The query on which you called `get` or `onSnapshot` in order to get this
1446 * `QuerySnapshot`.
1447 */
1448 readonly query: Query<T>;
1449
1450 /** An array of all the documents in the QuerySnapshot. */
1451 readonly docs: Array<QueryDocumentSnapshot<T>>;
1452
1453 /** The number of documents in the QuerySnapshot. */
1454 readonly size: number;
1455
1456 /** True if there are no documents in the QuerySnapshot. */
1457 readonly empty: boolean;
1458
1459 /** The time this query snapshot was obtained. */
1460 readonly readTime: Timestamp;
1461
1462 /**
1463 * Returns an array of the documents changes since the last snapshot. If
1464 * this is the first snapshot, all documents will be in the list as added
1465 * changes.
1466 */
1467 docChanges(): DocumentChange[];
1468
1469 /**
1470 * Enumerates all of the documents in the QuerySnapshot.
1471 *
1472 * @param callback A callback to be called with a `DocumentSnapshot` for
1473 * each document in the snapshot.
1474 * @param thisArg The `this` binding for the callback.
1475 */
1476 forEach(
1477 callback: (result: QueryDocumentSnapshot<T>) => void,
1478 thisArg?: any
1479 ): void;
1480
1481 /**
1482 * Returns true if the document data in this `QuerySnapshot` is equal to the
1483 * provided one.
1484 *
1485 * @param other The `QuerySnapshot` to compare against.
1486 * @return true if this `QuerySnapshot` is equal to the provided one.
1487 */
1488 isEqual(other: QuerySnapshot<T>): boolean;
1489 }
1490
1491 /**
1492 * The type of of a `DocumentChange` may be 'added', 'removed', or 'modified'.
1493 */
1494 export type DocumentChangeType = 'added' | 'removed' | 'modified';
1495
1496 /**
1497 * A `DocumentChange` represents a change to the documents matching a query.
1498 * It contains the document affected and the type of change that occurred.
1499 */
1500 export interface DocumentChange<T = DocumentData> {
1501 /** The type of change ('added', 'modified', or 'removed'). */
1502 readonly type: DocumentChangeType;
1503
1504 /** The document affected by this change. */
1505 readonly doc: QueryDocumentSnapshot<T>;
1506
1507 /**
1508 * The index of the changed document in the result set immediately prior to
1509 * this DocumentChange (i.e. supposing that all prior DocumentChange objects
1510 * have been applied). Is -1 for 'added' events.
1511 */
1512 readonly oldIndex: number;
1513
1514 /**
1515 * The index of the changed document in the result set immediately after
1516 * this DocumentChange (i.e. supposing that all prior DocumentChange
1517 * objects and the current DocumentChange object have been applied).
1518 * Is -1 for 'removed' events.
1519 */
1520 readonly newIndex: number;
1521
1522 /**
1523 * Returns true if the data in this `DocumentChange` is equal to the
1524 * provided one.
1525 *
1526 * @param other The `DocumentChange` to compare against.
1527 * @return true if this `DocumentChange` is equal to the provided one.
1528 */
1529 isEqual(other: DocumentChange<T>): boolean;
1530 }
1531
1532 /**
1533 * A `CollectionReference` object can be used for adding documents, getting
1534 * document references, and querying for documents (using the methods
1535 * inherited from `Query`).
1536 */
1537 export class CollectionReference<T = DocumentData> extends Query<T> {
1538 private constructor();
1539
1540 /** The identifier of the collection. */
1541 readonly id: string;
1542
1543 /**
1544 * A reference to the containing Document if this is a subcollection, else
1545 * null.
1546 */
1547 readonly parent: DocumentReference<DocumentData> | null;
1548
1549 /**
1550 * A string representing the path of the referenced collection (relative
1551 * to the root of the database).
1552 */
1553 readonly path: string;
1554
1555 /**
1556 * Retrieves the list of documents in this collection.
1557 *
1558 * The document references returned may include references to "missing
1559 * documents", i.e. document locations that have no document present but
1560 * which contain subcollections with documents. Attempting to read such a
1561 * document reference (e.g. via `.get()` or `.onSnapshot()`) will return a
1562 * `DocumentSnapshot` whose `.exists` property is false.
1563 *
1564 * @return {Promise<DocumentReference[]>} The list of documents in this
1565 * collection.
1566 */
1567 listDocuments(): Promise<Array<DocumentReference<T>>>;
1568
1569 /**
1570 * Get a `DocumentReference` for a randomly-named document within this
1571 * collection. An automatically-generated unique ID will be used as the
1572 * document ID.
1573 *
1574 * @return The `DocumentReference` instance.
1575 */
1576 doc(): DocumentReference<T>;
1577
1578 /**
1579 * Get a `DocumentReference` for the document within the collection at the
1580 * specified path.
1581 *
1582 * @param documentPath A slash-separated path to a document.
1583 * @return The `DocumentReference` instance.
1584 */
1585 doc(documentPath: string): DocumentReference<T>;
1586
1587 /**
1588 * Add a new document to this collection with the specified data, assigning
1589 * it a document ID automatically.
1590 *
1591 * @param data An Object containing the data for the new document.
1592 * @return A Promise resolved with a `DocumentReference` pointing to the
1593 * newly created document after it has been written to the backend.
1594 */
1595 add(data: T): Promise<DocumentReference<T>>;
1596
1597 /**
1598 * Returns true if this `CollectionReference` is equal to the provided one.
1599 *
1600 * @param other The `CollectionReference` to compare against.
1601 * @return true if this `CollectionReference` is equal to the provided one.
1602 */
1603 isEqual(other: CollectionReference<T>): boolean;
1604
1605 /**
1606 * Applies a custom data converter to this CollectionReference, allowing you
1607 * to use your own custom model objects with Firestore. When you call add()
1608 * on the returned CollectionReference instance, the provided converter will
1609 * convert between Firestore data and your custom type U.
1610 *
1611 * @param converter Converts objects to and from Firestore. Passing in
1612 * `null` removes the current converter.
1613 * @return A CollectionReference<U> that uses the provided converter.
1614 */
1615 withConverter<U>(
1616 converter: FirestoreDataConverter<U>
1617 ): CollectionReference<U>;
1618 withConverter(converter: null): CollectionReference<DocumentData>;
1619 }
1620
1621 /**
1622 * A `CollectionGroup` refers to all documents that are contained in a
1623 * collection or subcollection with a specific collection ID.
1624 */
1625 export class CollectionGroup<T = DocumentData> extends Query<T> {
1626 private constructor();
1627
1628 /**
1629 * Partitions a query by returning partition cursors that can be used to run
1630 * the query in parallel. The returned cursors are split points that can be
1631 * used as starting and end points for individual query invocations.
1632 *
1633 * @param desiredPartitionCount The desired maximum number of partition
1634 * points. The number must be strictly positive. The actual number of
1635 * partitions returned may be fewer.
1636 * @return An AsyncIterable of `QueryPartition`s.
1637 */
1638 getPartitions(
1639 desiredPartitionCount: number
1640 ): AsyncIterable<QueryPartition<T>>;
1641
1642 /**
1643 * Applies a custom data converter to this `CollectionGroup`, allowing you
1644 * to use your own custom model objects with Firestore. When you call get()
1645 * on the returned `CollectionGroup`, the provided converter will convert
1646 * between Firestore data and your custom type U.
1647 *
1648 * Using the converter allows you to specify generic type arguments when
1649 * storing and retrieving objects from Firestore.
1650 *
1651 * @example
1652 * class Post {
1653 * constructor(readonly title: string, readonly author: string) {}
1654 *
1655 * toString(): string {
1656 * return this.title + ', by ' + this.author;
1657 * }
1658 * }
1659 *
1660 * const postConverter = {
1661 * toFirestore(post: Post): FirebaseFirestore.DocumentData {
1662 * return {title: post.title, author: post.author};
1663 * },
1664 * fromFirestore(
1665 * snapshot: FirebaseFirestore.QueryDocumentSnapshot
1666 * ): Post {
1667 * const data = snapshot.data();
1668 * return new Post(data.title, data.author);
1669 * }
1670 * };
1671 *
1672 * const querySnapshot = await Firestore()
1673 * .collectionGroup('posts')
1674 * .withConverter(postConverter)
1675 * .get();
1676 * for (const doc of querySnapshot.docs) {
1677 * const post = doc.data();
1678 * post.title; // string
1679 * post.toString(); // Should be defined
1680 * post.someNonExistentProperty; // TS error
1681 * }
1682 *
1683 * @param converter Converts objects to and from Firestore. Passing in
1684 * `null` removes the current converter.
1685 * @return A `CollectionGroup<U>` that uses the provided converter.
1686 */
1687 withConverter<U>(converter: FirestoreDataConverter<U>): CollectionGroup<U>;
1688 withConverter(converter: null): CollectionGroup<DocumentData>;
1689 }
1690
1691 /**
1692 * A split point that can be used in a query as a starting and/or end point for
1693 * the query results. The cursors returned by {@link #startAt} and {@link
1694 * #endBefore} can only be used in a query that matches the constraint of query
1695 * that produced this partition.
1696 */
1697 export class QueryPartition<T = DocumentData> {
1698 private constructor();
1699
1700 /**
1701 * The cursor that defines the first result for this partition or
1702 * `undefined` if this is the first partition. The cursor value must be
1703 * destructured when passed to `startAt()` (for example with
1704 * `query.startAt(...queryPartition.startAt)`).
1705 *
1706 * @return Cursor values that can be used with {@link Query#startAt} or
1707 * `undefined` if this is the first partition.
1708 */
1709 get startAt(): unknown[] | undefined;
1710
1711 /**
1712 * The cursor that defines the first result after this partition or
1713 * `undefined` if this is the last partition. The cursor value must be
1714 * destructured when passed to `endBefore()` (for example with
1715 * `query.endBefore(...queryPartition.endBefore)`).
1716 *
1717 * @return Cursor values that can be used with {@link Query#endBefore} or
1718 * `undefined` if this is the last partition.
1719 */
1720 get endBefore(): unknown[] | undefined;
1721
1722 /**
1723 * Returns a query that only returns the documents for this partition.
1724 *
1725 * @return A query partitioned by a {@link Query#startAt} and {@link
1726 * Query#endBefore} cursor.
1727 */
1728 toQuery(): Query<T>;
1729 }
1730
1731 /**
1732 * Sentinel values that can be used when writing document fields with set(),
1733 * create() or update().
1734 */
1735 export class FieldValue {
1736 private constructor();
1737
1738 /**
1739 * Returns a sentinel used with set(), create() or update() to include a
1740 * server-generated timestamp in the written data.
1741 *
1742 * @return The FieldValue sentinel for use in a call to set(), create() or
1743 * update().
1744 */
1745 static serverTimestamp(): FieldValue;
1746
1747 /**
1748 * Returns a sentinel for use with update() or set() with {merge:true} to
1749 * mark a field for deletion.
1750 *
1751 * @return The FieldValue sentinel for use in a call to set() or update().
1752 */
1753 static delete(): FieldValue;
1754
1755 /**
1756 * Returns a special value that can be used with set(), create() or update()
1757 * that tells the server to increment the field's current value by the given
1758 * value.
1759 *
1760 * If either current field value or the operand uses floating point
1761 * precision, both values will be interpreted as floating point numbers and
1762 * all arithmetic will follow IEEE 754 semantics. Otherwise, integer
1763 * precision is kept and the result is capped between -2^63 and 2^63-1.
1764 *
1765 * If the current field value is not of type 'number', or if the field does
1766 * not yet exist, the transformation will set the field to the given value.
1767 *
1768 * @param n The value to increment by.
1769 * @return The FieldValue sentinel for use in a call to set(), create() or
1770 * update().
1771 */
1772 static increment(n: number): FieldValue;
1773
1774 /**
1775 * Returns a special value that can be used with set(), create() or update()
1776 * that tells the server to union the given elements with any array value
1777 * that already exists on the server. Each specified element that doesn't
1778 * already exist in the array will be added to the end. If the field being
1779 * modified is not already an array it will be overwritten with an array
1780 * containing exactly the specified elements.
1781 *
1782 * @param elements The elements to union into the array.
1783 * @return The FieldValue sentinel for use in a call to set(), create() or
1784 * update().
1785 */
1786 static arrayUnion(...elements: any[]): FieldValue;
1787
1788 /**
1789 * Returns a special value that can be used with set(), create() or update()
1790 * that tells the server to remove the given elements from any array value
1791 * that already exists on the server. All instances of each element
1792 * specified will be removed from the array. If the field being modified is
1793 * not already an array it will be overwritten with an empty array.
1794 *
1795 * @param elements The elements to remove from the array.
1796 * @return The FieldValue sentinel for use in a call to set(), create() or
1797 * update().
1798 */
1799 static arrayRemove(...elements: any[]): FieldValue;
1800
1801 /**
1802 * Returns true if this `FieldValue` is equal to the provided one.
1803 *
1804 * @param other The `FieldValue` to compare against.
1805 * @return true if this `FieldValue` is equal to the provided one.
1806 */
1807 isEqual(other: FieldValue): boolean;
1808 }
1809
1810 /**
1811 * A FieldPath refers to a field in a document. The path may consist of a
1812 * single field name (referring to a top-level field in the document), or a
1813 * list of field names (referring to a nested field in the document).
1814 */
1815 export class FieldPath {
1816 /**
1817 * Creates a FieldPath from the provided field names. If more than one field
1818 * name is provided, the path will point to a nested field in a document.
1819 *
1820 * @param fieldNames A list of field names.
1821 */
1822 constructor(...fieldNames: string[]);
1823
1824 /**
1825 * Returns a special sentinel FieldPath to refer to the ID of a document.
1826 * It can be used in queries to sort or filter by the document ID.
1827 */
1828 static documentId(): FieldPath;
1829
1830 /**
1831 * Returns true if this `FieldPath` is equal to the provided one.
1832 *
1833 * @param other The `FieldPath` to compare against.
1834 * @return true if this `FieldPath` is equal to the provided one.
1835 */
1836 isEqual(other: FieldPath): boolean;
1837 }
1838
1839 /**
1840 * A Timestamp represents a point in time independent of any time zone or
1841 * calendar, represented as seconds and fractions of seconds at nanosecond
1842 * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian
1843 * Calendar which extends the Gregorian calendar backwards to year one. It is
1844 * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are
1845 * "smeared" so that no leap second table is needed for interpretation. Range
1846 * is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
1847 *
1848 * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto
1849 */
1850 export class Timestamp {
1851 /**
1852 * Creates a new timestamp with the current date, with millisecond precision.
1853 *
1854 * @return A new `Timestamp` representing the current date.
1855 */
1856 static now(): Timestamp;
1857
1858 /**
1859 * Creates a new timestamp from the given date.
1860 *
1861 * @param date The date to initialize the `Timestamp` from.
1862 * @return A new `Timestamp` representing the same point in time as the
1863 * given date.
1864 */
1865 static fromDate(date: Date): Timestamp;
1866
1867 /**
1868 * Creates a new timestamp from the given number of milliseconds.
1869 *
1870 * @param milliseconds Number of milliseconds since Unix epoch
1871 * 1970-01-01T00:00:00Z.
1872 * @return A new `Timestamp` representing the same point in time as the
1873 * given number of milliseconds.
1874 */
1875 static fromMillis(milliseconds: number): Timestamp;
1876
1877 /**
1878 * Creates a new timestamp.
1879 *
1880 * @param seconds The number of seconds of UTC time since Unix epoch
1881 * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
1882 * 9999-12-31T23:59:59Z inclusive.
1883 * @param nanoseconds The non-negative fractions of a second at nanosecond
1884 * resolution. Negative second values with fractions must still have
1885 * non-negative nanoseconds values that count forward in time. Must be from
1886 * 0 to 999,999,999 inclusive.
1887 */
1888 constructor(seconds: number, nanoseconds: number);
1889
1890 /**
1891 * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
1892 */
1893 readonly seconds: number;
1894
1895 /** The non-negative fractions of a second at nanosecond resolution. */
1896 readonly nanoseconds: number;
1897
1898 /**
1899 * Returns a new `Date` corresponding to this timestamp. This may lose
1900 * precision.
1901 *
1902 * @return JavaScript `Date` object representing the same point in time as
1903 * this `Timestamp`, with millisecond precision.
1904 */
1905 toDate(): Date;
1906
1907 /**
1908 * Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
1909 *
1910 * @return The point in time corresponding to this timestamp, represented as
1911 * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
1912 */
1913 toMillis(): number;
1914
1915 /**
1916 * Returns true if this `Timestamp` is equal to the provided one.
1917 *
1918 * @param other The `Timestamp` to compare against.
1919 * @return 'true' if this `Timestamp` is equal to the provided one.
1920 */
1921 isEqual(other: Timestamp): boolean;
1922
1923 /**
1924 * Converts this object to a primitive `string`, which allows `Timestamp` objects to be compared
1925 * using the `>`, `<=`, `>=` and `>` operators.
1926 *
1927 * @return a string encoding of this object.
1928 */
1929 valueOf(): string;
1930 }
1931
1932 /**
1933 * Builds a Firestore data bundle with results from the given document and query snapshots.
1934 */
1935 export class BundleBuilder {
1936 /** The ID of this bundle. */
1937 readonly bundleId: string;
1938
1939 /**
1940 * Adds a Firestore `DocumentSnapshot` to the bundle. Both the documents data and the document
1941 * read time will be included in the bundle.
1942 *
1943 * @param documentSnapshot A `DocumentSnapshot` to add.
1944 * @returns This instance.
1945 */
1946 add<T>(documentSnapshot: DocumentSnapshot<T>): BundleBuilder;
1947
1948 /**
1949 * Adds a Firestore `QuerySnapshot` to the bundle. Both the documents in the query results and
1950 * the query read time will be included in the bundle.
1951 *
1952 * @param queryName The name of the query to add.
1953 * @param querySnapshot A `QuerySnapshot` to add to the bundle.
1954 * @returns This instance.
1955 */
1956 add<T>(queryName: string, querySnapshot: QuerySnapshot<T>): BundleBuilder;
1957
1958 /**
1959 * Builds the bundle and returns the result as a `Buffer` instance.
1960 */
1961 build(): Buffer;
1962 }
1963
1964 /**
1965 * The v1beta1 Veneer client. This client provides access to to the underlying
1966 * Firestore v1beta1 RPCs.
1967 * @deprecated Use v1 instead.
1968 */
1969 export const v1beta1: {
1970 FirestoreClient: typeof import('./v1beta1/firestore_client').FirestoreClient;
1971 };
1972
1973 /**
1974 * The v1 Veneer clients. These clients provide access to the Firestore Admin
1975 * API and the underlying Firestore v1 RPCs.
1976 */
1977 export const v1: {
1978 FirestoreClient: typeof import('./v1/firestore_client').FirestoreClient;
1979 FirestoreAdminClient: typeof import('./v1/firestore_admin_client').FirestoreAdminClient;
1980 };
1981
1982 /**
1983 * Status codes returned by Firestore's gRPC calls.
1984 */
1985 export enum GrpcStatus {
1986 OK = 0,
1987 CANCELLED = 1,
1988 UNKNOWN = 2,
1989 INVALID_ARGUMENT = 3,
1990 DEADLINE_EXCEEDED = 4,
1991 NOT_FOUND = 5,
1992 ALREADY_EXISTS = 6,
1993 PERMISSION_DENIED = 7,
1994 RESOURCE_EXHAUSTED = 8,
1995 FAILED_PRECONDITION = 9,
1996 ABORTED = 10,
1997 OUT_OF_RANGE = 11,
1998 UNIMPLEMENTED = 12,
1999 INTERNAL = 13,
2000 UNAVAILABLE = 14,
2001 DATA_LOSS = 15,
2002 UNAUTHENTICATED = 16,
2003 }
2004}
2005
2006declare module '@google-cloud/firestore' {
2007 export = FirebaseFirestore;
2008}