write-batch.d.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /*!
  2. * Copyright 2019 Google Inc. All Rights Reserved.
  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. import * as firestore from '@google-cloud/firestore';
  17. import { google } from '../protos/firestore_v1_proto_api';
  18. import { Firestore } from './index';
  19. import { FieldPath } from './path';
  20. import { Timestamp } from './timestamp';
  21. import { FirestoreUnaryMethod } from './types';
  22. import { RequiredArgumentOptions } from './validate';
  23. import api = google.firestore.v1;
  24. /**
  25. * A WriteResult wraps the write time set by the Firestore servers on sets(),
  26. * updates(), and creates().
  27. *
  28. * @class WriteResult
  29. */
  30. export declare class WriteResult implements firestore.WriteResult {
  31. private readonly _writeTime;
  32. /**
  33. * @private
  34. *
  35. * @param _writeTime The time of the corresponding document write.
  36. */
  37. constructor(_writeTime: Timestamp);
  38. /**
  39. * The write time as set by the Firestore servers.
  40. *
  41. * @type {Timestamp}
  42. * @name WriteResult#writeTime
  43. * @readonly
  44. *
  45. * @example
  46. * ```
  47. * let documentRef = firestore.doc('col/doc');
  48. *
  49. * documentRef.set({foo: 'bar'}).then(writeResult => {
  50. * console.log(`Document written at: ${writeResult.writeTime.toDate()}`);
  51. * });
  52. * ```
  53. */
  54. get writeTime(): Timestamp;
  55. /**
  56. * Returns true if this `WriteResult` is equal to the provided value.
  57. *
  58. * @param {*} other The value to compare against.
  59. * @return true if this `WriteResult` is equal to the provided value.
  60. */
  61. isEqual(other: firestore.WriteResult): boolean;
  62. }
  63. /**
  64. * A lazily-evaluated write that allows us to detect the Project ID before
  65. * serializing the request.
  66. * @private
  67. * @internal
  68. */
  69. export type PendingWriteOp = () => api.IWrite;
  70. /**
  71. * A Firestore WriteBatch that can be used to atomically commit multiple write
  72. * operations at once.
  73. *
  74. * @class WriteBatch
  75. */
  76. export declare class WriteBatch implements firestore.WriteBatch {
  77. protected readonly _firestore: Firestore;
  78. private readonly _serializer;
  79. private readonly _allowUndefined;
  80. /**
  81. * An array of document paths and the corresponding write operations that are
  82. * executed as part of the commit. The resulting `api.IWrite` will be sent to
  83. * the backend.
  84. *
  85. * @private
  86. * @internal
  87. */
  88. private readonly _ops;
  89. private _committed;
  90. /**
  91. * The number of writes in this batch.
  92. * @private
  93. * @internal
  94. */
  95. get _opCount(): number;
  96. /** @private */
  97. constructor(firestore: Firestore);
  98. /**
  99. * Checks if this write batch has any pending operations.
  100. *
  101. * @private
  102. * @internal
  103. */
  104. get isEmpty(): boolean;
  105. /**
  106. * Throws an error if this batch has already been committed.
  107. *
  108. * @private
  109. * @internal
  110. */
  111. private verifyNotCommitted;
  112. /**
  113. * Create a document with the provided object values. This will fail the batch
  114. * if a document exists at its location.
  115. *
  116. * @param {DocumentReference} documentRef A reference to the document to be
  117. * created.
  118. * @param {T} data The object to serialize as the document.
  119. * @throws {Error} If the provided input is not a valid Firestore document.
  120. * @returns {WriteBatch} This WriteBatch instance. Used for chaining
  121. * method calls.
  122. *
  123. * @example
  124. * ```
  125. * let writeBatch = firestore.batch();
  126. * let documentRef = firestore.collection('col').doc();
  127. *
  128. * writeBatch.create(documentRef, {foo: 'bar'});
  129. *
  130. * writeBatch.commit().then(() => {
  131. * console.log('Successfully executed batch.');
  132. * });
  133. * ```
  134. */
  135. create<AppModelType, DbModelType extends firestore.DocumentData>(documentRef: firestore.DocumentReference<AppModelType, DbModelType>, data: firestore.WithFieldValue<AppModelType>): WriteBatch;
  136. /**
  137. * Deletes a document from the database.
  138. *
  139. * @param {DocumentReference} documentRef A reference to the document to be
  140. * deleted.
  141. * @param {Precondition=} precondition A precondition to enforce for this
  142. * delete.
  143. * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
  144. * document was last updated at lastUpdateTime. Fails the batch if the
  145. * document doesn't exist or was last updated at a different time.
  146. * @param {boolean= } precondition.exists If set to true, enforces that the target
  147. * document must or must not exist.
  148. * @returns {WriteBatch} This WriteBatch instance. Used for chaining
  149. * method calls.
  150. *
  151. * @example
  152. * ```
  153. * let writeBatch = firestore.batch();
  154. * let documentRef = firestore.doc('col/doc');
  155. *
  156. * writeBatch.delete(documentRef);
  157. *
  158. * writeBatch.commit().then(() => {
  159. * console.log('Successfully executed batch.');
  160. * });
  161. * ```
  162. */
  163. delete(documentRef: firestore.DocumentReference<any, any>, precondition?: firestore.Precondition): WriteBatch;
  164. set<AppModelType, DbModelType extends firestore.DocumentData>(documentRef: firestore.DocumentReference<AppModelType, DbModelType>, data: firestore.PartialWithFieldValue<AppModelType>, options: firestore.SetOptions): WriteBatch;
  165. set<AppModelType, DbModelType extends firestore.DocumentData>(documentRef: firestore.DocumentReference<AppModelType, DbModelType>, data: firestore.WithFieldValue<AppModelType>): WriteBatch;
  166. /**
  167. * Update fields of the document referred to by the provided
  168. * [DocumentReference]{@link DocumentReference}. If the document
  169. * doesn't yet exist, the update fails and the entire batch will be rejected.
  170. *
  171. * The update() method accepts either an object with field paths encoded as
  172. * keys and field values encoded as values, or a variable number of arguments
  173. * that alternate between field paths and field values. Nested fields can be
  174. * updated by providing dot-separated field path strings or by providing
  175. * FieldPath objects.
  176. *
  177. * A Precondition restricting this update can be specified as the last
  178. * argument.
  179. *
  180. * @param {DocumentReference} documentRef A reference to the document to be
  181. * updated.
  182. * @param {UpdateData|string|FieldPath} dataOrField An object
  183. * containing the fields and values with which to update the document
  184. * or the path of the first field to update.
  185. * @param {
  186. * ...(Precondition|*|string|FieldPath)} preconditionOrValues -
  187. * An alternating list of field paths and values to update or a Precondition
  188. * to restrict this update.
  189. * @throws {Error} If the provided input is not valid Firestore data.
  190. * @returns {WriteBatch} This WriteBatch instance. Used for chaining
  191. * method calls.
  192. *
  193. * @example
  194. * ```
  195. * let writeBatch = firestore.batch();
  196. * let documentRef = firestore.doc('col/doc');
  197. *
  198. * writeBatch.update(documentRef, {foo: 'bar'});
  199. *
  200. * writeBatch.commit().then(() => {
  201. * console.log('Successfully executed batch.');
  202. * });
  203. * ```
  204. */
  205. update<AppModelType = firestore.DocumentData, DbModelType extends firestore.DocumentData = firestore.DocumentData>(documentRef: firestore.DocumentReference<AppModelType, DbModelType>, dataOrField: firestore.UpdateData<DbModelType> | string | firestore.FieldPath, ...preconditionOrValues: Array<{
  206. lastUpdateTime?: firestore.Timestamp;
  207. } | unknown | string | firestore.FieldPath>): WriteBatch;
  208. /**
  209. * Atomically commits all pending operations to the database and verifies all
  210. * preconditions. Fails the entire write if any precondition is not met.
  211. *
  212. * @returns {Promise.<Array.<WriteResult>>} A Promise that resolves
  213. * when this batch completes.
  214. *
  215. * @example
  216. * ```
  217. * let writeBatch = firestore.batch();
  218. * let documentRef = firestore.doc('col/doc');
  219. *
  220. * writeBatch.set(documentRef, {foo: 'bar'});
  221. *
  222. * writeBatch.commit().then(() => {
  223. * console.log('Successfully executed batch.');
  224. * });
  225. * ```
  226. */
  227. commit(): Promise<WriteResult[]>;
  228. /**
  229. * Commit method that takes an optional transaction ID.
  230. *
  231. * @private
  232. * @internal
  233. * @param commitOptions Options to use for this commit.
  234. * @param commitOptions.transactionId The transaction ID of this commit.
  235. * @param commitOptions.requestTag A unique client-assigned identifier for
  236. * this request.
  237. * @returns A Promise that resolves when this batch completes.
  238. */
  239. _commit<Req extends api.ICommitRequest, Resp>(commitOptions?: {
  240. transactionId?: Uint8Array;
  241. requestTag?: string;
  242. retryCodes?: number[];
  243. methodName?: FirestoreUnaryMethod;
  244. }): Promise<Resp>;
  245. /**
  246. * Resets the WriteBatch and dequeues all pending operations.
  247. * @private
  248. * @internal
  249. */
  250. _reset(): void;
  251. }
  252. /**
  253. * Validates the use of 'value' as SetOptions and enforces that 'merge' is a
  254. * boolean.
  255. *
  256. * @private
  257. * @internal
  258. * @param arg The argument name or argument index (for varargs methods).
  259. * @param value The object to validate.
  260. * @param options Optional validation options specifying whether the value can
  261. * be omitted.
  262. * @throws if the input is not a valid SetOptions object.
  263. */
  264. export declare function validateSetOptions(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void;
  265. /**
  266. * Validates a JavaScript object for usage as a Firestore document.
  267. *
  268. * @private
  269. * @internal
  270. * @param arg The argument name or argument index (for varargs methods).
  271. * @param obj JavaScript object to validate.
  272. * @param allowDeletes Whether to allow FieldValue.delete() sentinels.
  273. * @param allowUndefined Whether to allow nested properties that are `undefined`.
  274. * @throws when the object is invalid.
  275. */
  276. export declare function validateDocumentData(arg: string | number, obj: unknown, allowDeletes: boolean, allowUndefined: boolean): void;
  277. /**
  278. * Validates that a value can be used as field value during an update.
  279. *
  280. * @private
  281. * @internal
  282. * @param arg The argument name or argument index (for varargs methods).
  283. * @param val The value to verify.
  284. * @param allowUndefined Whether to allow nested properties that are `undefined`.
  285. * @param path The path to show in the error message.
  286. */
  287. export declare function validateFieldValue(arg: string | number, val: unknown, allowUndefined: boolean, path?: FieldPath): void;