@google-cloud/firestore
Version:
Firestore Client Library for Node.js
1,061 lines • 78.4 kB
JavaScript
"use strict";
// Copyright 2026 Google LLC
//
// 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
//
// https://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.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
Object.defineProperty(exports, "__esModule", { value: true });
exports.FirestoreClient = void 0;
const stream_1 = require("stream");
const jsonProtos = require("../../protos/v1.json");
const google_gax_1 = require("google-gax");
/**
* Client JSON configuration object, loaded from
* `src/v1/firestore_client_config.json`.
* This file defines retry strategy and timeouts for all API methods in this library.
*/
const gapicConfig = require("./firestore_client_config.json");
const version = require('../../../package.json').version;
/**
* The Cloud Firestore service.
*
* Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL
* document database that simplifies storing, syncing, and querying data for
* your mobile, web, and IoT apps at global scale. Its client libraries provide
* live synchronization and offline support, while its security features and
* integrations with Firebase and Google Cloud Platform accelerate building
* truly serverless apps.
* @class
* @memberof v1
*/
class FirestoreClient {
_terminated = false;
_opts;
_providedCustomServicePath;
_gaxModule;
_gaxGrpc;
_protos;
_defaults;
_universeDomain;
_servicePath;
_log = google_gax_1.loggingUtils.log('firestore');
auth;
descriptors = {
page: {},
stream: {},
longrunning: {},
batching: {},
};
warn;
innerApiCalls;
locationsClient;
firestoreStub;
/**
* Construct an instance of FirestoreClient.
*
* @param {object} [options] - The configuration object.
* The options accepted by the constructor are described in detail
* in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance).
* The common options are:
* @param {object} [options.credentials] - Credentials object.
* @param {string} [options.credentials.client_email]
* @param {string} [options.credentials.private_key]
* @param {string} [options.email] - Account email address. Required when
* using a .pem or .p12 keyFilename.
* @param {string} [options.keyFilename] - Full path to the a .json, .pem, or
* .p12 key downloaded from the Google Developers Console. If you provide
* a path to a JSON file, the projectId option below is not necessary.
* NOTE: .pem and .p12 require you to specify options.email as well.
* @param {number} [options.port] - The port on which to connect to
* the remote host.
* @param {string} [options.projectId] - The project ID from the Google
* Developer's Console, e.g. 'grape-spaceship-123'. We will also check
* the environment variable GCLOUD_PROJECT for your project ID. If your
* app is running in an environment which supports
* {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
* @param {gax.ClientConfig} [options.clientConfig] - Client configuration override.
* Follows the structure of {@link gapicConfig}.
* @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode.
* For more information, please check the
* {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}.
* @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you
* need to avoid loading the default gRPC version and want to use the fallback
* HTTP implementation. Load only fallback version and pass it to the constructor:
* ```
* const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC
* const client = new FirestoreClient({fallback: true}, gax);
* ```
*/
constructor(opts, gaxInstance) {
// Ensure that options include all the required fields.
const staticMembers = this.constructor;
if (opts?.universe_domain &&
opts?.universeDomain &&
opts?.universe_domain !== opts?.universeDomain) {
throw new Error('Please set either universe_domain or universeDomain, but not both.');
}
const universeDomainEnvVar = typeof process === 'object' && typeof process.env === 'object'
? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']
: undefined;
this._universeDomain =
opts?.universeDomain ??
opts?.universe_domain ??
universeDomainEnvVar ??
'googleapis.com';
this._servicePath = 'firestore.' + this._universeDomain;
const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath;
this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint);
const port = opts?.port || staticMembers.port;
const clientConfig = opts?.clientConfig ?? {};
const fallback = opts?.fallback ??
(typeof window !== 'undefined' && typeof window?.fetch === 'function');
opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts);
// Request numeric enum values if REST transport is used.
opts.numericEnums = true;
// If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case.
if (servicePath !== this._servicePath && !('scopes' in opts)) {
opts['scopes'] = staticMembers.scopes;
}
// Load google-gax module synchronously if needed
if (!gaxInstance) {
gaxInstance = require('google-gax');
}
// Choose either gRPC or proto-over-HTTP implementation of google-gax.
this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance;
// Create a `gaxGrpc` object, with any grpc-specific options sent to the client.
this._gaxGrpc = new this._gaxModule.GrpcClient(opts);
// Save options to use in initialize() method.
this._opts = opts;
// Save the auth object to the client, for use by other methods.
this.auth = this._gaxGrpc.auth;
// Set useJWTAccessWithScope on the auth object.
this.auth.useJWTAccessWithScope = true;
// Set defaultServicePath on the auth object.
this.auth.defaultServicePath = this._servicePath;
// Set the default scopes in auth client if needed.
if (servicePath === this._servicePath) {
this.auth.defaultScopes = staticMembers.scopes;
}
this.locationsClient = new this._gaxModule.LocationsClient(this._gaxGrpc, opts);
// Determine the client header string.
const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`];
if (typeof process === 'object' && 'versions' in process) {
clientHeader.push(`gl-node/${process.versions.node}`);
}
else {
clientHeader.push(`gl-web/${this._gaxModule.version}`);
}
if (!opts.fallback) {
clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`);
}
else {
clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`);
}
if (opts.libName && opts.libVersion) {
clientHeader.push(`${opts.libName}/${opts.libVersion}`);
}
// Load the applicable protos.
this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos);
// Some of the methods on this service return "paged" results,
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this.descriptors.page = {
listDocuments: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'),
partitionQuery: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'partitions'),
listCollectionIds: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'collectionIds'),
};
// Some of the methods on this service provide streaming responses.
// Provide descriptors for these.
this.descriptors.stream = {
batchGetDocuments: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries),
runQuery: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries),
executePipeline: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries),
runAggregationQuery: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries),
write: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries),
listen: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries),
};
// Put together the default options sent with requests.
this._defaults = this._gaxGrpc.constructSettings('google.firestore.v1.Firestore', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') });
// Set up a dictionary of "inner API calls"; the core implementation
// of calling the API is handled in `google-gax`, with this code
// merely providing the destination and request information.
this.innerApiCalls = {};
// Add a warn function to the client constructor so it can be easily tested.
this.warn = this._gaxModule.warn;
}
/**
* Initialize the client.
* Performs asynchronous operations (such as authentication) and prepares the client.
* This function will be called automatically when any class method is called for the
* first time, but if you need to initialize it before calling an actual method,
* feel free to call initialize() directly.
*
* You can await on this method if you want to make sure the client is initialized.
*
* @returns {Promise} A promise that resolves to an authenticated service stub.
*/
initialize() {
// If the client stub promise is already initialized, return immediately.
if (this.firestoreStub) {
return this.firestoreStub;
}
// Put together the "service stub" for
// google.firestore.v1.Firestore.
this.firestoreStub = this._gaxGrpc.createStub(this._opts.fallback
? this._protos.lookupService('google.firestore.v1.Firestore')
: // eslint-disable-next-line @typescript-eslint/no-explicit-any
this._protos.google.firestore.v1.Firestore, this._opts, this._providedCustomServicePath);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const firestoreStubMethods = [
'getDocument',
'listDocuments',
'updateDocument',
'deleteDocument',
'batchGetDocuments',
'beginTransaction',
'commit',
'rollback',
'runQuery',
'executePipeline',
'runAggregationQuery',
'partitionQuery',
'write',
'listen',
'listCollectionIds',
'batchWrite',
'createDocument',
];
for (const methodName of firestoreStubMethods) {
const callPromise = this.firestoreStub.then(stub => (...args) => {
if (this._terminated) {
if (methodName in this.descriptors.stream) {
const stream = new stream_1.PassThrough({ objectMode: true });
setImmediate(() => {
stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.'));
});
return stream;
}
return Promise.reject('The client has already been closed.');
}
const func = stub[methodName];
return func.apply(stub, args);
}, (err) => () => {
throw err;
});
const descriptor = this.descriptors.page[methodName] ||
this.descriptors.stream[methodName] ||
undefined;
const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor, this._opts.fallback);
this.innerApiCalls[methodName] = apiCall;
}
return this.firestoreStub;
}
/**
* The DNS address for this API service.
* @deprecated Use the apiEndpoint method of the client instance.
* @returns {string} The DNS address for this service.
*/
static get servicePath() {
if (typeof process === 'object' &&
typeof process.emitWarning === 'function') {
process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning');
}
return 'firestore.googleapis.com';
}
/**
* The DNS address for this API service - same as servicePath.
* @deprecated Use the apiEndpoint method of the client instance.
* @returns {string} The DNS address for this service.
*/
static get apiEndpoint() {
if (typeof process === 'object' &&
typeof process.emitWarning === 'function') {
process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning');
}
return 'firestore.googleapis.com';
}
/**
* The DNS address for this API service.
* @returns {string} The DNS address for this service.
*/
get apiEndpoint() {
return this._servicePath;
}
get universeDomain() {
return this._universeDomain;
}
/**
* The port for this API service.
* @returns {number} The default port for this service.
*/
static get port() {
return 443;
}
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
* @returns {string[]} List of default scopes.
*/
static get scopes() {
return [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/datastore',
];
}
/**
* Return the project ID used by this class.
* @returns {Promise} A promise that resolves to string containing the project ID.
*/
getProjectId(callback) {
if (callback) {
this.auth.getProjectId(callback);
return;
}
return this.auth.getProjectId();
}
getDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
name: request.name ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('getDocument request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('getDocument response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.getDocument(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('getDocument response %j', response);
return [response, options, rawResponse];
})
.catch((error) => {
if (error &&
'statusDetails' in error &&
error.statusDetails instanceof Array) {
const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
error.statusDetails = (0, google_gax_1.decodeAnyProtosInArray)(error.statusDetails, protos);
}
throw error;
});
}
updateDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
'document.name': request.document.name ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('updateDocument request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('updateDocument response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.updateDocument(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('updateDocument response %j', response);
return [response, options, rawResponse];
})
.catch((error) => {
if (error &&
'statusDetails' in error &&
error.statusDetails instanceof Array) {
const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
error.statusDetails = (0, google_gax_1.decodeAnyProtosInArray)(error.statusDetails, protos);
}
throw error;
});
}
deleteDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
name: request.name ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('deleteDocument request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('deleteDocument response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.deleteDocument(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('deleteDocument response %j', response);
return [response, options, rawResponse];
})
.catch((error) => {
if (error &&
'statusDetails' in error &&
error.statusDetails instanceof Array) {
const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
error.statusDetails = (0, google_gax_1.decodeAnyProtosInArray)(error.statusDetails, protos);
}
throw error;
});
}
beginTransaction(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
database: request.database ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('beginTransaction request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('beginTransaction response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.beginTransaction(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('beginTransaction response %j', response);
return [response, options, rawResponse];
})
.catch((error) => {
if (error &&
'statusDetails' in error &&
error.statusDetails instanceof Array) {
const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
error.statusDetails = (0, google_gax_1.decodeAnyProtosInArray)(error.statusDetails, protos);
}
throw error;
});
}
commit(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
database: request.database ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('commit request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('commit response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.commit(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('commit response %j', response);
return [response, options, rawResponse];
})
.catch((error) => {
if (error &&
'statusDetails' in error &&
error.statusDetails instanceof Array) {
const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
error.statusDetails = (0, google_gax_1.decodeAnyProtosInArray)(error.statusDetails, protos);
}
throw error;
});
}
rollback(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
database: request.database ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('rollback request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('rollback response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.rollback(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('rollback response %j', response);
return [response, options, rawResponse];
})
.catch((error) => {
if (error &&
'statusDetails' in error &&
error.statusDetails instanceof Array) {
const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
error.statusDetails = (0, google_gax_1.decodeAnyProtosInArray)(error.statusDetails, protos);
}
throw error;
});
}
batchWrite(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
database: request.database ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('batchWrite request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('batchWrite response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.batchWrite(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('batchWrite response %j', response);
return [response, options, rawResponse];
})
.catch((error) => {
if (error &&
'statusDetails' in error &&
error.statusDetails instanceof Array) {
const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
error.statusDetails = (0, google_gax_1.decodeAnyProtosInArray)(error.statusDetails, protos);
}
throw error;
});
}
createDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
parent: request.parent ?? '',
collection_id: request.collectionId?.toString() ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('createDocument request %j', request);
const wrappedCallback = callback
? (error, response, options, rawResponse) => {
this._log.info('createDocument response %j', response);
callback(error, response, options, rawResponse); // We verified callback above.
}
: undefined;
return this.innerApiCalls
.createDocument(request, options, wrappedCallback)
?.then(([response, options, rawResponse]) => {
this._log.info('createDocument response %j', response);
return [response, options, rawResponse];
})
.catch((error) => {
if (error &&
'statusDetails' in error &&
error.statusDetails instanceof Array) {
const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos);
error.statusDetails = (0, google_gax_1.decodeAnyProtosInArray)(error.statusDetails, protos);
}
throw error;
});
}
/**
* Gets multiple documents.
*
* Documents returned by this method are not guaranteed to be returned in the
* same order that they were requested.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.database
* Required. The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
* @param {string[]} request.documents
* The names of the documents to retrieve. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* The request will fail if any of the document is not a child resource of the
* given `database`. Duplicate names will be elided.
* @param {google.firestore.v1.DocumentMask} request.mask
* The fields to return. If not set, returns all fields.
*
* If a document has a field that is not present in this mask, that field will
* not be returned in the response.
* @param {Buffer} request.transaction
* Reads documents in a transaction.
* @param {google.firestore.v1.TransactionOptions} request.newTransaction
* Starts a new transaction and reads the documents.
* Defaults to a read-only transaction.
* The new transaction ID will be returned as the first response in the
* stream.
* @param {google.protobuf.Timestamp} request.readTime
* Reads documents as they were at the given time.
*
* This must be a microsecond precision timestamp within the past one hour,
* or if Point-in-Time Recovery is enabled, can additionally be a whole
* minute timestamp within the past 7 days.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event.
* Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation }
* for more details and examples.
* @example <caption>include:samples/generated/v1/firestore.batch_get_documents.js</caption>
* region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async
*/
batchGetDocuments(request, options) {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
database: request.database ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('batchGetDocuments stream %j', options);
return this.innerApiCalls.batchGetDocuments(request, options);
}
/**
* Runs a query.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent resource name. In the format:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents` or
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
* @param {google.firestore.v1.StructuredQuery} request.structuredQuery
* A structured query.
* @param {Buffer} request.transaction
* Run the query within an already active transaction.
*
* The value here is the opaque transaction ID to execute the query in.
* @param {google.firestore.v1.TransactionOptions} request.newTransaction
* Starts a new transaction and reads the documents.
* Defaults to a read-only transaction.
* The new transaction ID will be returned as the first response in the
* stream.
* @param {google.protobuf.Timestamp} request.readTime
* Reads documents as they were at the given time.
*
* This must be a microsecond precision timestamp within the past one hour,
* or if Point-in-Time Recovery is enabled, can additionally be a whole
* minute timestamp within the past 7 days.
* @param {google.firestore.v1.ExplainOptions} [request.explainOptions]
* Optional. Explain options for the query. If set, additional query
* statistics will be returned. If not, only query results will be returned.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event.
* Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation }
* for more details and examples.
* @example <caption>include:samples/generated/v1/firestore.run_query.js</caption>
* region_tag:firestore_v1_generated_Firestore_RunQuery_async
*/
runQuery(request, options) {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
parent: request.parent ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('runQuery stream %j', options);
return this.innerApiCalls.runQuery(request, options);
}
/**
* Executes a pipeline query.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.database
* Required. Database identifier, in the form
* `projects/{project}/databases/{database}`.
* @param {google.firestore.v1.StructuredPipeline} request.structuredPipeline
* A pipelined operation.
* @param {Buffer} request.transaction
* Run the query within an already active transaction.
*
* The value here is the opaque transaction ID to execute the query in.
* @param {google.firestore.v1.TransactionOptions} request.newTransaction
* Execute the pipeline in a new transaction.
*
* The identifier of the newly created transaction will be returned in the
* first response on the stream. This defaults to a read-only transaction.
* @param {google.protobuf.Timestamp} request.readTime
* Execute the pipeline in a snapshot transaction at the given time.
*
* This must be a microsecond precision timestamp within the past one hour,
* or if Point-in-Time Recovery is enabled, can additionally be a whole
* minute timestamp within the past 7 days.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits {@link protos.google.firestore.v1.ExecutePipelineResponse|ExecutePipelineResponse} on 'data' event.
* Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation }
* for more details and examples.
* @example <caption>include:samples/generated/v1/firestore.execute_pipeline.js</caption>
* region_tag:firestore_v1_generated_Firestore_ExecutePipeline_async
*/
executePipeline(request, options) {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
const routingParameter = {};
{
const fieldValue = request.database;
if (fieldValue !== undefined && fieldValue !== null) {
const match = fieldValue
.toString()
.match(RegExp('projects/(?<project_id>[^/]+)(?:/.*)?'));
if (match) {
const parameterValue = match.groups?.['project_id'] ?? fieldValue;
Object.assign(routingParameter, { project_id: parameterValue });
}
}
}
{
const fieldValue = request.database;
if (fieldValue !== undefined && fieldValue !== null) {
const match = fieldValue
.toString()
.match(RegExp('projects/[^/]+/databases/(?<database_id>[^/]+)(?:/.*)?'));
if (match) {
const parameterValue = match.groups?.['database_id'] ?? fieldValue;
Object.assign(routingParameter, { database_id: parameterValue });
}
}
}
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams(routingParameter);
this.initialize().catch(err => {
throw err;
});
this._log.info('executePipeline stream %j', options);
return this.innerApiCalls.executePipeline(request, options);
}
/**
* Runs an aggregation query.
*
* Rather than producing {@link protos.google.firestore.v1.Document|Document} results like
* {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API
* allows running an aggregation to produce a series of
* {@link protos.google.firestore.v1.AggregationResult|AggregationResult} server-side.
*
* High-Level Example:
*
* ```
* -- Return the number of documents in table given a filter.
* SELECT COUNT(*) FROM ( SELECT * FROM k where a = true );
* ```
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent resource name. In the format:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents` or
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
* @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery
* An aggregation query.
* @param {Buffer} request.transaction
* Run the aggregation within an already active transaction.
*
* The value here is the opaque transaction ID to execute the query in.
* @param {google.firestore.v1.TransactionOptions} request.newTransaction
* Starts a new transaction as part of the query, defaulting to read-only.
*
* The new transaction ID will be returned as the first response in the
* stream.
* @param {google.protobuf.Timestamp} request.readTime
* Executes the query at the given timestamp.
*
* This must be a microsecond precision timestamp within the past one hour,
* or if Point-in-Time Recovery is enabled, can additionally be a whole
* minute timestamp within the past 7 days.
* @param {google.firestore.v1.ExplainOptions} [request.explainOptions]
* Optional. Explain options for the query. If set, additional query
* statistics will be returned. If not, only query results will be returned.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event.
* Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation }
* for more details and examples.
* @example <caption>include:samples/generated/v1/firestore.run_aggregation_query.js</caption>
* region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async
*/
runAggregationQuery(request, options) {
request = request || {};
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
parent: request.parent ?? '',
});
this.initialize().catch(err => {
throw err;
});
this._log.info('runAggregationQuery stream %j', options);
return this.innerApiCalls.runAggregationQuery(request, options);
}
/**
* Streams batches of document updates and deletes, in order. This method is
* only available via gRPC or WebChannel (not REST).
*
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which is both readable and writable. It accepts objects
* representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and
* will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously.
* Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation }
* for more details and examples.
* @example <caption>include:samples/generated/v1/firestore.write.js</caption>
* region_tag:firestore_v1_generated_Firestore_Write_async
*/
write(options) {
this.initialize().catch(err => {
throw err;
});
this._log.info('write stream %j', options);
return this.innerApiCalls.write(null, options);
}
/**
* Listens to changes. This method is only available via gRPC or WebChannel
* (not REST).
*
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which is both readable and writable. It accepts objects
* representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and
* will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously.
* Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation }
* for more details and examples.
* @example <caption>include:samples/generated/v1/firestore.listen.js</caption>
* region_tag:firestore_v1_generated_Firestore_Listen_async
*/
listen(options) {
this.initialize().catch(err => {
throw err;
});
this._log.info('listen stream %j', options);
return this.innerApiCalls.listen(null, options);
}
listDocuments(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
this._gaxModule.routingHeader.fromParams({
parent: request.parent ?? '',
collection_id: request.collectionId?.toString() ?? '',
});
this.initialize().catch(err => {
throw err;
});
const wrappedCallback = callback
? (error, values, nextPageRequest, rawResponse) => {
this._log.info('listDocuments values %j', values);
callback(error, values, nextPageRequest, rawResponse); // We verified callback above.
}
: undefined;
this._log.info('listDocuments request %j', request);
return this.innerApiCalls
.listDocuments(request, options, wrappedCallback)
?.then(([response, input, output]) => {
this._log.info('listDocuments values %j', response);
return [response, input, output];
});
}
/**
* Equivalent to `listDocuments`, but returns a NodeJS Stream object.
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent resource name. In the format:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* For example:
* `projects/my-project/databases/my-database/documents` or
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
* @param {string} [request.collectionId]
* Optional. The collection ID, relative to `parent`, to list.
*
* For example: `chatrooms` or `messages`.
*
* This is optional, and when not provided, Firestore will list documents
* from all collections under the provided `parent`.
* @param {number} [request.pageSize]
* Optional. The maximum number of documents to return in a single response.
*
* Firestore may return fewer than this value.
* @param {string} [request.pageToken]
* Optional. A page token, received from a previous `ListDocuments` response.
*
* Provide this to retrieve the subsequent page. When paginating, all other
* parameters (with the exception of `page_size`) must match the values set
* in the request that generated the page token.
* @param {string} [request.orderBy]
* Optional. The optional ordering of the documents to return.
*
* For example: `priority desc, __name__ desc`.
*
* This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`}
* used in Firestore queries but in a string representation. When absent,
* documents are ordered based on `__name__ ASC`.
* @param {google.firestore.v1.DocumentMask} [request.mask]
* Optional. The fields to return. If not set, returns all fields.
*
* If a document has a field that is not present in this mask, that field
* will not be returned in the response.
* @param {Buffer} request.transaction
* Perform the read as part of an already active transaction.
* @param {google.protobuf.Timestamp} request.readTime
* Perform the read at the provided time.
*
* This must be a microsecond precision timestamp within the past one hour,
* or if Point-in-Time Recovery is enabled, can additionally be a whole
* minute timestamp within the past 7 days.
* @param {boolean} request.showMissing
* If