1
0
mirror of https://github.com/musix-org/musix-oss synced 2025-06-17 13:56:01 +00:00
This commit is contained in:
MatteZ02
2020-03-03 22:30:50 +02:00
parent edfcc6f474
commit 30022c7634
11800 changed files with 1984416 additions and 1 deletions

View File

@ -0,0 +1,146 @@
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*!
* The maximum number of retries that will be attempted by backoff
* before stopping all retry attempts.
*/
export declare const MAX_RETRY_ATTEMPTS = 10;
/**
* Allows overriding of the timeout handler used by the exponential backoff
* implementation. If not invoked, we default to `setTimeout()`.
*
* Used only in testing.
*
* @private
* @param {function} handler A handler than matches the API of `setTimeout()`.
*/
export declare function setTimeoutHandler(handler: (f: () => void, ms: number) => void): void;
/**
* Configuration object to adjust the delays of the exponential backoff
* algorithm.
*
* @private
*/
export interface ExponentialBackoffSetting {
/** Optional override for the initial retry delay. */
initialDelayMs?: number;
/** Optional override for the exponential backoff factor. */
backoffFactor?: number;
/** Optional override for the maximum retry delay. */
maxDelayMs?: number;
/**
* Optional override to control the itter factor by which to randomize
* attempts (0 means no randomization, 1.0 means +/-50% randomization). It is
* suggested not to exceed this range.
*/
jitterFactor?: number;
}
/**
* A helper for running delayed tasks following an exponential backoff curve
* between attempts.
*
* Each delay is made up of a "base" delay which follows the exponential
* backoff curve, and a "jitter" (+/- 50% by default) that is calculated and
* added to the base delay. This prevents clients from accidentally
* synchronizing their delays causing spikes of load to the backend.
*
* @private
*/
export declare class ExponentialBackoff {
/**
* The initial delay (used as the base delay on the first retry attempt).
* Note that jitter will still be applied, so the actual delay could be as
* little as 0.5*initialDelayMs (based on a jitter factor of 1.0).
*
* @private
*/
private readonly initialDelayMs;
/**
* The multiplier to use to determine the extended base delay after each
* attempt.
*
* @private
*/
private readonly backoffFactor;
/**
* The maximum base delay after which no further backoff is performed.
* Note that jitter will still be applied, so the actual delay could be as
* much as 1.5*maxDelayMs (based on a jitter factor of 1.0).
*
* @private
*/
private readonly maxDelayMs;
/**
* The jitter factor that controls the random distribution of the backoff
* points.
*
* @private
*/
private readonly jitterFactor;
/**
* The number of retries that has been attempted.
*
* @private
*/
private _retryCount;
/**
* The backoff delay of the current attempt.
*
* @private
*/
private currentBaseMs;
/**
* Whether we are currently waiting for backoff to complete.
*
* @private
*/
private awaitingBackoffCompletion;
constructor(options?: ExponentialBackoffSetting);
/**
* Resets the backoff delay and retry count.
*
* The very next backoffAndWait() will have no delay. If it is called again
* (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
* subsequent ones will increase according to the backoffFactor.
*
* @private
*/
reset(): void;
/**
* Resets the backoff delay to the maximum delay (e.g. for use after a
* RESOURCE_EXHAUSTED error).
*
* @private
*/
resetToMax(): void;
/**
* Returns a promise that resolves after currentDelayMs, and increases the
* delay for any subsequent attempts.
*
* @return A Promise that resolves when the current delay elapsed.
* @private
*/
backoffAndWait(): Promise<void>;
readonly retryCount: number;
/**
* Returns a randomized "jitter" delay based on the current base and jitter
* factor.
*
* @returns {number} The jitter to apply based on the current delay.
* @private
*/
private jitterDelayMs;
}

View File

@ -0,0 +1,189 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("./logger");
/*
* @module firestore/backoff
* @private
*
* Contains backoff logic to facilitate RPC error handling. This class derives
* its implementation from the Firestore Mobile Web Client.
*
* @see https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore/src/remote/backoff.ts
*/
/*!
* The default initial backoff time in milliseconds after an error.
* Set to 1s according to https://cloud.google.com/apis/design/errors.
*/
const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;
/*!
* The default maximum backoff time in milliseconds.
*/
const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;
/*!
* The default factor to increase the backup by after each failed attempt.
*/
const DEFAULT_BACKOFF_FACTOR = 1.5;
/*!
* The default jitter to distribute the backoff attempts by (0 means no
* randomization, 1.0 means +/-50% randomization).
*/
const DEFAULT_JITTER_FACTOR = 1.0;
/*!
* The maximum number of retries that will be attempted by backoff
* before stopping all retry attempts.
*/
exports.MAX_RETRY_ATTEMPTS = 10;
/*!
* The timeout handler used by `ExponentialBackoff`.
*/
let delayExecution = setTimeout;
/**
* Allows overriding of the timeout handler used by the exponential backoff
* implementation. If not invoked, we default to `setTimeout()`.
*
* Used only in testing.
*
* @private
* @param {function} handler A handler than matches the API of `setTimeout()`.
*/
function setTimeoutHandler(handler) {
delayExecution = handler;
}
exports.setTimeoutHandler = setTimeoutHandler;
/**
* A helper for running delayed tasks following an exponential backoff curve
* between attempts.
*
* Each delay is made up of a "base" delay which follows the exponential
* backoff curve, and a "jitter" (+/- 50% by default) that is calculated and
* added to the base delay. This prevents clients from accidentally
* synchronizing their delays causing spikes of load to the backend.
*
* @private
*/
class ExponentialBackoff {
constructor(options = {}) {
/**
* The number of retries that has been attempted.
*
* @private
*/
this._retryCount = 0;
/**
* The backoff delay of the current attempt.
*
* @private
*/
this.currentBaseMs = 0;
/**
* Whether we are currently waiting for backoff to complete.
*
* @private
*/
this.awaitingBackoffCompletion = false;
this.initialDelayMs =
options.initialDelayMs !== undefined
? options.initialDelayMs
: DEFAULT_BACKOFF_INITIAL_DELAY_MS;
this.backoffFactor =
options.backoffFactor !== undefined
? options.backoffFactor
: DEFAULT_BACKOFF_FACTOR;
this.maxDelayMs =
options.maxDelayMs !== undefined
? options.maxDelayMs
: DEFAULT_BACKOFF_MAX_DELAY_MS;
this.jitterFactor =
options.jitterFactor !== undefined
? options.jitterFactor
: DEFAULT_JITTER_FACTOR;
}
/**
* Resets the backoff delay and retry count.
*
* The very next backoffAndWait() will have no delay. If it is called again
* (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
* subsequent ones will increase according to the backoffFactor.
*
* @private
*/
reset() {
this._retryCount = 0;
this.currentBaseMs = 0;
}
/**
* Resets the backoff delay to the maximum delay (e.g. for use after a
* RESOURCE_EXHAUSTED error).
*
* @private
*/
resetToMax() {
this.currentBaseMs = this.maxDelayMs;
}
/**
* Returns a promise that resolves after currentDelayMs, and increases the
* delay for any subsequent attempts.
*
* @return A Promise that resolves when the current delay elapsed.
* @private
*/
backoffAndWait() {
if (this.awaitingBackoffCompletion) {
return Promise.reject(new Error('A backoff operation is already in progress.'));
}
if (this.retryCount > exports.MAX_RETRY_ATTEMPTS) {
return Promise.reject(new Error('Exceeded maximum number of retries allowed.'));
}
// First schedule using the current base (which may be 0 and should be
// honored as such).
const delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();
if (this.currentBaseMs > 0) {
logger_1.logger('ExponentialBackoff.backoffAndWait', null, `Backing off for ${delayWithJitterMs} ms ` +
`(base delay: ${this.currentBaseMs} ms)`);
}
// Apply backoff factor to determine next delay and ensure it is within
// bounds.
this.currentBaseMs *= this.backoffFactor;
this.currentBaseMs = Math.max(this.currentBaseMs, this.initialDelayMs);
this.currentBaseMs = Math.min(this.currentBaseMs, this.maxDelayMs);
this._retryCount += 1;
return new Promise(resolve => {
this.awaitingBackoffCompletion = true;
delayExecution(() => {
this.awaitingBackoffCompletion = false;
resolve();
}, delayWithJitterMs);
});
}
// Visible for testing.
get retryCount() {
return this._retryCount;
}
/**
* Returns a randomized "jitter" delay based on the current base and jitter
* factor.
*
* @returns {number} The jitter to apply based on the current delay.
* @private
*/
jitterDelayMs() {
return (Math.random() - 0.5) * this.jitterFactor * this.currentBaseMs;
}
}
exports.ExponentialBackoff = ExponentialBackoff;
//# sourceMappingURL=backoff.js.map

View File

@ -0,0 +1,67 @@
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { google } from '../protos/firestore_v1_proto_api';
import { ApiMapValue, ProtobufJsValue } from './types';
import api = google.firestore.v1;
/*!
* @module firestore/convert
* @private
*
* This module contains utility functions to convert
* `firestore.v1.Documents` from Proto3 JSON to their equivalent
* representation in Protobuf JS. Protobuf JS is the only encoding supported by
* this client, and dependencies that use Proto3 JSON (such as the Google Cloud
* Functions SDK) are supported through this conversion and its usage in
* {@see Firestore#snapshot_}.
*/
/**
* Converts an ISO 8601 or google.protobuf.Timestamp proto into Protobuf JS.
*
* @private
* @param timestampValue The value to convert.
* @param argumentName The argument name to use in the error message if the
* conversion fails. If omitted, 'timestampValue' is used.
* @return The value as expected by Protobuf JS or undefined if no input was
* provided.
*/
export declare function timestampFromJson(timestampValue?: string | google.protobuf.ITimestamp, argumentName?: string): google.protobuf.ITimestamp | undefined;
/**
* Detects 'valueType' from a Proto3 JSON `firestore.v1.Value` proto.
*
* @private
* @param proto The `firestore.v1.Value` proto.
* @return The string value for 'valueType'.
*/
export declare function detectValueType(proto: ProtobufJsValue): string;
/**
* Converts a `firestore.v1.Value` in Proto3 JSON encoding into the
* Protobuf JS format expected by this client.
*
* @private
* @param fieldValue The `firestore.v1.Value` in Proto3 JSON format.
* @return The `firestore.v1.Value` in Protobuf JS format.
*/
export declare function valueFromJson(fieldValue: api.IValue): api.IValue;
/**
* Converts a map of IValues in Proto3 JSON encoding into the Protobuf JS format
* expected by this client. This conversion creates a copy of the underlying
* fields.
*
* @private
* @param document An object with IValues in Proto3 JSON format.
* @return The object in Protobuf JS format.
*/
export declare function fieldsFromJson(document: ApiMapValue): ApiMapValue;

View File

@ -0,0 +1,212 @@
"use strict";
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("./validate");
/*!
* @module firestore/convert
* @private
*
* This module contains utility functions to convert
* `firestore.v1.Documents` from Proto3 JSON to their equivalent
* representation in Protobuf JS. Protobuf JS is the only encoding supported by
* this client, and dependencies that use Proto3 JSON (such as the Google Cloud
* Functions SDK) are supported through this conversion and its usage in
* {@see Firestore#snapshot_}.
*/
/**
* Converts an ISO 8601 or google.protobuf.Timestamp proto into Protobuf JS.
*
* @private
* @param timestampValue The value to convert.
* @param argumentName The argument name to use in the error message if the
* conversion fails. If omitted, 'timestampValue' is used.
* @return The value as expected by Protobuf JS or undefined if no input was
* provided.
*/
function timestampFromJson(timestampValue, argumentName) {
let timestampProto;
if (typeof timestampValue === 'string') {
const date = new Date(timestampValue);
const seconds = Math.floor(date.getTime() / 1000);
let nanos = 0;
if (timestampValue.length > 20) {
const nanoString = timestampValue.substring(20, timestampValue.length - 1);
const trailingZeroes = 9 - nanoString.length;
nanos = Number(nanoString) * Math.pow(10, trailingZeroes);
}
if (isNaN(seconds) || isNaN(nanos)) {
argumentName = argumentName || 'timestampValue';
throw new Error(`Specify a valid ISO 8601 timestamp for "${argumentName}".`);
}
timestampProto = {
seconds: seconds || undefined,
nanos: nanos || undefined,
};
}
else if (timestampValue !== undefined) {
validate_1.validateObject('timestampValue', timestampValue);
timestampProto = {
seconds: timestampValue.seconds || undefined,
nanos: timestampValue.nanos || undefined,
};
}
return timestampProto;
}
exports.timestampFromJson = timestampFromJson;
/**
* Converts a Proto3 JSON 'bytesValue' field into Protobuf JS.
*
* @private
* @param bytesValue The value to convert.
* @return The value as expected by Protobuf JS.
*/
function bytesFromJson(bytesValue) {
if (typeof bytesValue === 'string') {
return Buffer.from(bytesValue, 'base64');
}
else {
return bytesValue;
}
}
/**
* Detects 'valueType' from a Proto3 JSON `firestore.v1.Value` proto.
*
* @private
* @param proto The `firestore.v1.Value` proto.
* @return The string value for 'valueType'.
*/
function detectValueType(proto) {
if (proto.valueType) {
return proto.valueType;
}
const detectedValues = [];
if (proto.stringValue !== undefined) {
detectedValues.push('stringValue');
}
if (proto.booleanValue !== undefined) {
detectedValues.push('booleanValue');
}
if (proto.integerValue !== undefined) {
detectedValues.push('integerValue');
}
if (proto.doubleValue !== undefined) {
detectedValues.push('doubleValue');
}
if (proto.timestampValue !== undefined) {
detectedValues.push('timestampValue');
}
if (proto.referenceValue !== undefined) {
detectedValues.push('referenceValue');
}
if (proto.arrayValue !== undefined) {
detectedValues.push('arrayValue');
}
if (proto.nullValue !== undefined) {
detectedValues.push('nullValue');
}
if (proto.mapValue !== undefined) {
detectedValues.push('mapValue');
}
if (proto.geoPointValue !== undefined) {
detectedValues.push('geoPointValue');
}
if (proto.bytesValue !== undefined) {
detectedValues.push('bytesValue');
}
if (detectedValues.length !== 1) {
throw new Error(`Unable to infer type value fom '${JSON.stringify(proto)}'.`);
}
return detectedValues[0];
}
exports.detectValueType = detectValueType;
/**
* Converts a `firestore.v1.Value` in Proto3 JSON encoding into the
* Protobuf JS format expected by this client.
*
* @private
* @param fieldValue The `firestore.v1.Value` in Proto3 JSON format.
* @return The `firestore.v1.Value` in Protobuf JS format.
*/
function valueFromJson(fieldValue) {
const valueType = detectValueType(fieldValue);
switch (valueType) {
case 'timestampValue':
return {
timestampValue: timestampFromJson(fieldValue.timestampValue),
};
case 'bytesValue':
return {
bytesValue: bytesFromJson(fieldValue.bytesValue),
};
case 'integerValue':
return {
integerValue: Number(fieldValue.integerValue),
};
case 'doubleValue':
return {
doubleValue: Number(fieldValue.doubleValue),
};
case 'arrayValue': {
const arrayValue = [];
if (Array.isArray(fieldValue.arrayValue.values)) {
for (const value of fieldValue.arrayValue.values) {
arrayValue.push(valueFromJson(value));
}
}
return {
arrayValue: {
values: arrayValue,
},
};
}
case 'mapValue': {
const mapValue = {};
const fields = fieldValue.mapValue.fields;
if (fields) {
for (const prop of Object.keys(fields)) {
mapValue[prop] = valueFromJson(fieldValue.mapValue.fields[prop]);
}
}
return {
mapValue: {
fields: mapValue,
},
};
}
default:
return fieldValue;
}
}
exports.valueFromJson = valueFromJson;
/**
* Converts a map of IValues in Proto3 JSON encoding into the Protobuf JS format
* expected by this client. This conversion creates a copy of the underlying
* fields.
*
* @private
* @param document An object with IValues in Proto3 JSON format.
* @return The object in Protobuf JS format.
*/
function fieldsFromJson(document) {
const result = {};
for (const prop of Object.keys(document)) {
result[prop] = valueFromJson(document[prop]);
}
return result;
}
exports.fieldsFromJson = fieldsFromJson;
//# sourceMappingURL=convert.js.map

View File

@ -0,0 +1,147 @@
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { QueryDocumentSnapshot } from './document';
import { DocumentData } from './types';
export declare type DocumentChangeType = 'added' | 'removed' | 'modified';
/**
* A DocumentChange represents a change to the documents matching a query.
* It contains the document affected and the type of change that occurred.
*
* @class
*/
export declare class DocumentChange<T = DocumentData> {
private readonly _type;
private readonly _document;
private readonly _oldIndex;
private readonly _newIndex;
/**
* @hideconstructor
*
* @param {string} type 'added' | 'removed' | 'modified'.
* @param {QueryDocumentSnapshot} document The document.
* @param {number} oldIndex The index in the documents array prior to this
* change.
* @param {number} newIndex The index in the documents array after this
* change.
*/
constructor(type: DocumentChangeType, document: QueryDocumentSnapshot<T>, oldIndex: number, newIndex: number);
/**
* The type of change ('added', 'modified', or 'removed').
*
* @type {string}
* @name DocumentChange#type
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
* let docsArray = [];
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* console.log(`Type of change is ${change.type}`);
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
readonly type: DocumentChangeType;
/**
* The document affected by this change.
*
* @type {QueryDocumentSnapshot}
* @name DocumentChange#doc
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* console.log(change.doc.data());
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
readonly doc: QueryDocumentSnapshot<T>;
/**
* The index of the changed document in the result set immediately prior to
* this DocumentChange (i.e. supposing that all prior DocumentChange objects
* have been applied). Is -1 for 'added' events.
*
* @type {number}
* @name DocumentChange#oldIndex
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
* let docsArray = [];
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* if (change.oldIndex !== -1) {
* docsArray.splice(change.oldIndex, 1);
* }
* if (change.newIndex !== -1) {
* docsArray.splice(change.newIndex, 0, change.doc);
* }
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
readonly oldIndex: number;
/**
* The index of the changed document in the result set immediately after
* this DocumentChange (i.e. supposing that all prior DocumentChange
* objects and the current DocumentChange object have been applied).
* Is -1 for 'removed' events.
*
* @type {number}
* @name DocumentChange#newIndex
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
* let docsArray = [];
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* if (change.oldIndex !== -1) {
* docsArray.splice(change.oldIndex, 1);
* }
* if (change.newIndex !== -1) {
* docsArray.splice(change.newIndex, 0, change.doc);
* }
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
readonly newIndex: number;
/**
* Returns true if the data in this `DocumentChange` is equal to the provided
* value.
*
* @param {*} other The value to compare against.
* @return true if this `DocumentChange` is equal to the provided value.
*/
isEqual(other: DocumentChange<T>): boolean;
}

View File

@ -0,0 +1,166 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A DocumentChange represents a change to the documents matching a query.
* It contains the document affected and the type of change that occurred.
*
* @class
*/
class DocumentChange {
/**
* @hideconstructor
*
* @param {string} type 'added' | 'removed' | 'modified'.
* @param {QueryDocumentSnapshot} document The document.
* @param {number} oldIndex The index in the documents array prior to this
* change.
* @param {number} newIndex The index in the documents array after this
* change.
*/
constructor(type, document, oldIndex, newIndex) {
this._type = type;
this._document = document;
this._oldIndex = oldIndex;
this._newIndex = newIndex;
}
/**
* The type of change ('added', 'modified', or 'removed').
*
* @type {string}
* @name DocumentChange#type
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
* let docsArray = [];
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* console.log(`Type of change is ${change.type}`);
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
get type() {
return this._type;
}
/**
* The document affected by this change.
*
* @type {QueryDocumentSnapshot}
* @name DocumentChange#doc
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* console.log(change.doc.data());
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
get doc() {
return this._document;
}
/**
* The index of the changed document in the result set immediately prior to
* this DocumentChange (i.e. supposing that all prior DocumentChange objects
* have been applied). Is -1 for 'added' events.
*
* @type {number}
* @name DocumentChange#oldIndex
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
* let docsArray = [];
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* if (change.oldIndex !== -1) {
* docsArray.splice(change.oldIndex, 1);
* }
* if (change.newIndex !== -1) {
* docsArray.splice(change.newIndex, 0, change.doc);
* }
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
get oldIndex() {
return this._oldIndex;
}
/**
* The index of the changed document in the result set immediately after
* this DocumentChange (i.e. supposing that all prior DocumentChange
* objects and the current DocumentChange object have been applied).
* Is -1 for 'removed' events.
*
* @type {number}
* @name DocumentChange#newIndex
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
* let docsArray = [];
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* if (change.oldIndex !== -1) {
* docsArray.splice(change.oldIndex, 1);
* }
* if (change.newIndex !== -1) {
* docsArray.splice(change.newIndex, 0, change.doc);
* }
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
get newIndex() {
return this._newIndex;
}
/**
* Returns true if the data in this `DocumentChange` is equal to the provided
* value.
*
* @param {*} other The value to compare against.
* @return true if this `DocumentChange` is equal to the provided value.
*/
isEqual(other) {
if (this === other) {
return true;
}
return (other instanceof DocumentChange &&
this._type === other._type &&
this._oldIndex === other._oldIndex &&
this._newIndex === other._newIndex &&
this._document.isEqual(other._document));
}
}
exports.DocumentChange = DocumentChange;
//# sourceMappingURL=document-change.js.map

View File

@ -0,0 +1,545 @@
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { google } from '../protos/firestore_v1_proto_api';
import { FieldTransform } from './field-value';
import { FieldPath } from './path';
import { DocumentReference } from './reference';
import { Serializer } from './serializer';
import { Timestamp } from './timestamp';
import { ApiMapValue, DocumentData, UpdateMap } from './types';
import api = google.firestore.v1;
/**
* Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances.
* Invoke `.build()' to assemble the final snapshot.
*
* @private
*/
export declare class DocumentSnapshotBuilder<T = DocumentData> {
readonly ref: DocumentReference<T>;
/** The fields of the Firestore `Document` Protobuf backing this document. */
fieldsProto?: ApiMapValue;
/** The time when this document was read. */
readTime?: Timestamp;
/** The time when this document was created. */
createTime?: Timestamp;
/** The time when this document was last updated. */
updateTime?: Timestamp;
constructor(ref: DocumentReference<T>);
/**
* Builds the DocumentSnapshot.
*
* @private
* @returns Returns either a QueryDocumentSnapshot (if `fieldsProto` was
* provided) or a DocumentSnapshot.
*/
build(): QueryDocumentSnapshot<T> | DocumentSnapshot<T>;
}
/**
* A DocumentSnapshot is an immutable representation for a document in a
* Firestore database. The data can be extracted with
* [data()]{@link DocumentSnapshot#data} or
* [get(fieldPath)]{@link DocumentSnapshot#get} to get a
* specific field.
*
* <p>For a DocumentSnapshot that points to a non-existing document, any data
* access will return 'undefined'. You can use the
* [exists]{@link DocumentSnapshot#exists} property to explicitly verify a
* document's existence.
*
* @class
*/
export declare class DocumentSnapshot<T = DocumentData> {
readonly _fieldsProto?: ApiMapValue | undefined;
private _ref;
private _serializer;
private _readTime;
private _createTime;
private _updateTime;
/**
* @hideconstructor
*
* @param ref The reference to the document.
* @param _fieldsProto The fields of the Firestore `Document` Protobuf backing
* this document (or undefined if the document does not exist).
* @param readTime The time when this snapshot was read (or undefined if
* the document exists only locally).
* @param createTime The time when the document was created (or undefined if
* the document does not exist).
* @param updateTime The time when the document was last updated (or undefined
* if the document does not exist).
*/
constructor(ref: DocumentReference<T>, _fieldsProto?: ApiMapValue | undefined, readTime?: Timestamp, createTime?: Timestamp, updateTime?: Timestamp);
/**
* Creates a DocumentSnapshot from an object.
*
* @private
* @param ref The reference to the document.
* @param obj The object to store in the DocumentSnapshot.
* @return The created DocumentSnapshot.
*/
static fromObject<U>(ref: DocumentReference<U>, obj: DocumentData): DocumentSnapshot<U>;
/**
* Creates a DocumentSnapshot from an UpdateMap.
*
* This methods expands the top-level field paths in a JavaScript map and
* turns { foo.bar : foobar } into { foo { bar : foobar }}
*
* @private
* @param ref The reference to the document.
* @param data The field/value map to expand.
* @return The created DocumentSnapshot.
*/
static fromUpdateMap<U>(ref: DocumentReference<U>, data: UpdateMap): DocumentSnapshot<U>;
/**
* True if the document exists.
*
* @type {boolean}
* @name DocumentSnapshot#exists
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Data: ${JSON.stringify(documentSnapshot.data())}`);
* }
* });
*/
readonly exists: boolean;
/**
* A [DocumentReference]{@link DocumentReference} for the document
* stored in this snapshot.
*
* @type {DocumentReference}
* @name DocumentSnapshot#ref
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Found document at '${documentSnapshot.ref.path}'`);
* }
* });
*/
readonly ref: DocumentReference<T>;
/**
* The ID of the document for which this DocumentSnapshot contains data.
*
* @type {string}
* @name DocumentSnapshot#id
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Document found with name '${documentSnapshot.id}'`);
* }
* });
*/
readonly id: string;
/**
* The time the document was created. Undefined for documents that don't
* exist.
*
* @type {Timestamp|undefined}
* @name DocumentSnapshot#createTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* if (documentSnapshot.exists) {
* let createTime = documentSnapshot.createTime;
* console.log(`Document created at '${createTime.toDate()}'`);
* }
* });
*/
readonly createTime: Timestamp | undefined;
/**
* The time the document was last updated (at the time the snapshot was
* generated). Undefined for documents that don't exist.
*
* @type {Timestamp|undefined}
* @name DocumentSnapshot#updateTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* if (documentSnapshot.exists) {
* let updateTime = documentSnapshot.updateTime;
* console.log(`Document updated at '${updateTime.toDate()}'`);
* }
* });
*/
readonly updateTime: Timestamp | undefined;
/**
* The time this snapshot was read.
*
* @type {Timestamp}
* @name DocumentSnapshot#readTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* let readTime = documentSnapshot.readTime;
* console.log(`Document read at '${readTime.toDate()}'`);
* });
*/
readonly readTime: Timestamp;
/**
* Retrieves all fields in the document as an object. Returns 'undefined' if
* the document doesn't exist.
*
* @returns {T|undefined} An object containing all fields in the document or
* 'undefined' if the document doesn't exist.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* let data = documentSnapshot.data();
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
data(): T | undefined;
/**
* Retrieves the field specified by `field`.
*
* @param {string|FieldPath} field The field path
* (e.g. 'foo' or 'foo.bar') to a specific field.
* @returns {*} The data at the specified field location or undefined if no
* such field exists.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ a: { b: 'c' }}).then(() => {
* return documentRef.get();
* }).then(documentSnapshot => {
* let field = documentSnapshot.get('a.b');
* console.log(`Retrieved field value: ${field}`);
* });
*/
get(field: string | FieldPath): any;
/**
* Retrieves the field specified by 'fieldPath' in its Protobuf JS
* representation.
*
* @private
* @param field The path (e.g. 'foo' or 'foo.bar') to a specific field.
* @returns The Protobuf-encoded data at the specified field location or
* undefined if no such field exists.
*/
protoField(field: string | FieldPath): api.IValue | undefined;
/**
* Checks whether this DocumentSnapshot contains any fields.
*
* @private
* @return {boolean}
*/
readonly isEmpty: boolean;
/**
* Convert a document snapshot to the Firestore 'Document' Protobuf.
*
* @private
* @returns The document in the format the API expects.
*/
toProto(): api.IWrite;
/**
* Returns true if the document's data and path in this `DocumentSnapshot` is
* equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `DocumentSnapshot` is equal to the provided
* value.
*/
isEqual(other: DocumentSnapshot<T>): boolean;
}
/**
* A QueryDocumentSnapshot contains data read from a document in your
* Firestore database as part of a query. The document is guaranteed to exist
* and its data can be extracted with [data()]{@link QueryDocumentSnapshot#data}
* or [get()]{@link DocumentSnapshot#get} to get a specific field.
*
* A QueryDocumentSnapshot offers the same API surface as a
* {@link DocumentSnapshot}. Since query results contain only existing
* documents, the [exists]{@link DocumentSnapshot#exists} property will
* always be true and [data()]{@link QueryDocumentSnapshot#data} will never
* return 'undefined'.
*
* @class
* @extends DocumentSnapshot
*/
export declare class QueryDocumentSnapshot<T = DocumentData> extends DocumentSnapshot<T> {
/**
* @hideconstructor
*
* @param ref The reference to the document.
* @param fieldsProto The fields of the Firestore `Document` Protobuf backing
* this document.
* @param readTime The time when this snapshot was read.
* @param createTime The time when the document was created.
* @param updateTime The time when the document was last updated.
*/
constructor(ref: DocumentReference<T>, fieldsProto: ApiMapValue, readTime: Timestamp, createTime: Timestamp, updateTime: Timestamp);
/**
* The time the document was created.
*
* @type {Timestamp}
* @name QueryDocumentSnapshot#createTime
* @readonly
* @override
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(snapshot => {
* console.log(`Document created at '${snapshot.createTime.toDate()}'`);
* });
*/
readonly createTime: Timestamp;
/**
* The time the document was last updated (at the time the snapshot was
* generated).
*
* @type {Timestamp}
* @name QueryDocumentSnapshot#updateTime
* @readonly
* @override
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(snapshot => {
* console.log(`Document updated at '${snapshot.updateTime.toDate()}'`);
* });
*/
readonly updateTime: Timestamp;
/**
* Retrieves all fields in the document as an object.
*
* @override
*
* @returns {T} An object containing all fields in the document.
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(documentSnapshot => {
* let data = documentSnapshot.data();
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
data(): T;
}
/**
* A Firestore Document Mask contains the field paths affected by an update.
*
* @class
* @private
*/
export declare class DocumentMask {
private _sortedPaths;
/**
* @private
* @hideconstructor
*
* @param fieldPaths The field paths in this mask.
*/
constructor(fieldPaths: FieldPath[]);
/**
* Creates a document mask with the field paths of a document.
*
* @private
* @param data A map with fields to modify. Only the keys are used to extract
* the document mask.
*/
static fromUpdateMap(data: UpdateMap): DocumentMask;
/**
* Creates a document mask from an array of field paths.
*
* @private
* @param fieldMask A list of field paths.
*/
static fromFieldMask(fieldMask: Array<string | FieldPath>): DocumentMask;
/**
* Creates a document mask with the field names of a document.
*
* @private
* @param data An object with fields to modify. Only the keys are used to
* extract the document mask.
*/
static fromObject(data: DocumentData): DocumentMask;
/**
* Returns true if this document mask contains no fields.
*
* @private
* @return {boolean} Whether this document mask is empty.
*/
readonly isEmpty: boolean;
/**
* Removes the specified values from a sorted field path array.
*
* @private
* @param input A sorted array of FieldPaths.
* @param values An array of FieldPaths to remove.
*/
private static removeFromSortedArray;
/**
* Removes the field path specified in 'fieldPaths' from this document mask.
*
* @private
* @param fieldPaths An array of FieldPaths.
*/
removeFields(fieldPaths: FieldPath[]): void;
/**
* Returns whether this document mask contains 'fieldPath'.
*
* @private
* @param fieldPath The field path to test.
* @return Whether this document mask contains 'fieldPath'.
*/
contains(fieldPath: FieldPath): boolean;
/**
* Removes all properties from 'data' that are not contained in this document
* mask.
*
* @private
* @param data An object to filter.
* @return A shallow copy of the object filtered by this document mask.
*/
applyTo(data: DocumentData): DocumentData;
/**
* Converts a document mask to the Firestore 'DocumentMask' Proto.
*
* @private
* @returns A Firestore 'DocumentMask' Proto.
*/
toProto(): api.IDocumentMask;
}
/**
* A Firestore Document Transform.
*
* A DocumentTransform contains pending server-side transforms and their
* corresponding field paths.
*
* @private
* @class
*/
export declare class DocumentTransform<T = DocumentData> {
private readonly ref;
private readonly transforms;
/**
* @private
* @hideconstructor
*
* @param ref The DocumentReference for this transform.
* @param transforms A Map of FieldPaths to FieldTransforms.
*/
constructor(ref: DocumentReference<T>, transforms: Map<FieldPath, FieldTransform>);
/**
* Generates a DocumentTransform from a JavaScript object.
*
* @private
* @param ref The `DocumentReference` to use for the DocumentTransform.
* @param obj The object to extract the transformations from.
* @returns The Document Transform.
*/
static fromObject<T>(ref: DocumentReference<T>, obj: DocumentData): DocumentTransform<T>;
/**
* Generates a DocumentTransform from an Update Map.
*
* @private
* @param ref The `DocumentReference` to use for the DocumentTransform.
* @param data The update data to extract the transformations from.
* @returns The Document Transform.
*/
static fromUpdateMap<T>(ref: DocumentReference<T>, data: UpdateMap): DocumentTransform<T>;
/**
* Whether this DocumentTransform contains any actionable transformations.
*
* @private
*/
readonly isEmpty: boolean;
/**
* Returns the array of fields in this DocumentTransform.
*
* @private
*/
readonly fields: FieldPath[];
/**
* Validates the user provided field values in this document transform.
* @private
*/
validate(): void;
/**
* Converts a document transform to the Firestore 'DocumentTransform' Proto.
*
* @private
* @param serializer The Firestore serializer
* @returns A Firestore 'DocumentTransform' Proto or 'null' if this transform
* is empty.
*/
toProto(serializer: Serializer): api.IWrite | null;
}
/**
* A Firestore Precondition encapsulates options for database writes.
*
* @private
* @class
*/
export declare class Precondition {
private _exists?;
private _lastUpdateTime?;
/**
* @private
* @hideconstructor
*
* @param options.exists - Whether the referenced document should exist in
* Firestore,
* @param options.lastUpdateTime - The last update time of the referenced
* document in Firestore.
* @param options
*/
constructor(options?: {
exists?: boolean;
lastUpdateTime?: Timestamp;
});
/**
* Generates the Protobuf `Preconditon` object for this precondition.
*
* @private
* @returns The `Preconditon` Protobuf object or 'null' if there are no
* preconditions.
*/
toProto(): api.IPrecondition | null;
/**
* Whether this DocumentTransform contains any enforcement.
*
* @private
*/
readonly isEmpty: boolean;
}

View File

@ -0,0 +1,884 @@
"use strict";
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const deepEqual = require('deep-equal');
const assert = require("assert");
const field_value_1 = require("./field-value");
const path_1 = require("./path");
const util_1 = require("./util");
/**
* Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances.
* Invoke `.build()' to assemble the final snapshot.
*
* @private
*/
class DocumentSnapshotBuilder {
// We include the DocumentReference in the constructor in order to allow the
// DocumentSnapshotBuilder to be typed with <T> when it is constructed.
constructor(ref) {
this.ref = ref;
}
/**
* Builds the DocumentSnapshot.
*
* @private
* @returns Returns either a QueryDocumentSnapshot (if `fieldsProto` was
* provided) or a DocumentSnapshot.
*/
build() {
assert((this.fieldsProto !== undefined) === (this.createTime !== undefined), 'Create time should be set iff document exists.');
assert((this.fieldsProto !== undefined) === (this.updateTime !== undefined), 'Update time should be set iff document exists.');
return this.fieldsProto
? new QueryDocumentSnapshot(this.ref, this.fieldsProto, this.readTime, this.createTime, this.updateTime)
: new DocumentSnapshot(this.ref, undefined, this.readTime);
}
}
exports.DocumentSnapshotBuilder = DocumentSnapshotBuilder;
/**
* A DocumentSnapshot is an immutable representation for a document in a
* Firestore database. The data can be extracted with
* [data()]{@link DocumentSnapshot#data} or
* [get(fieldPath)]{@link DocumentSnapshot#get} to get a
* specific field.
*
* <p>For a DocumentSnapshot that points to a non-existing document, any data
* access will return 'undefined'. You can use the
* [exists]{@link DocumentSnapshot#exists} property to explicitly verify a
* document's existence.
*
* @class
*/
class DocumentSnapshot {
/**
* @hideconstructor
*
* @param ref The reference to the document.
* @param _fieldsProto The fields of the Firestore `Document` Protobuf backing
* this document (or undefined if the document does not exist).
* @param readTime The time when this snapshot was read (or undefined if
* the document exists only locally).
* @param createTime The time when the document was created (or undefined if
* the document does not exist).
* @param updateTime The time when the document was last updated (or undefined
* if the document does not exist).
*/
constructor(ref, _fieldsProto, readTime, createTime, updateTime) {
this._fieldsProto = _fieldsProto;
this._ref = ref;
this._serializer = ref.firestore._serializer;
this._readTime = readTime;
this._createTime = createTime;
this._updateTime = updateTime;
}
/**
* Creates a DocumentSnapshot from an object.
*
* @private
* @param ref The reference to the document.
* @param obj The object to store in the DocumentSnapshot.
* @return The created DocumentSnapshot.
*/
static fromObject(ref, obj) {
const serializer = ref.firestore._serializer;
return new DocumentSnapshot(ref, serializer.encodeFields(obj));
}
/**
* Creates a DocumentSnapshot from an UpdateMap.
*
* This methods expands the top-level field paths in a JavaScript map and
* turns { foo.bar : foobar } into { foo { bar : foobar }}
*
* @private
* @param ref The reference to the document.
* @param data The field/value map to expand.
* @return The created DocumentSnapshot.
*/
static fromUpdateMap(ref, data) {
const serializer = ref.firestore._serializer;
/**
* Merges 'value' at the field path specified by the path array into
* 'target'.
*/
function merge(target, value, path, pos) {
const key = path[pos];
const isLast = pos === path.length - 1;
if (target[key] === undefined) {
if (isLast) {
if (value instanceof field_value_1.FieldTransform) {
// If there is already data at this path, we need to retain it.
// Otherwise, we don't include it in the DocumentSnapshot.
return !util_1.isEmpty(target) ? target : null;
}
// The merge is done.
const leafNode = serializer.encodeValue(value);
if (leafNode) {
target[key] = leafNode;
}
return target;
}
else {
// We need to expand the target object.
const childNode = {
mapValue: {
fields: {},
},
};
const nestedValue = merge(childNode.mapValue.fields, value, path, pos + 1);
if (nestedValue) {
childNode.mapValue.fields = nestedValue;
target[key] = childNode;
return target;
}
else {
return !util_1.isEmpty(target) ? target : null;
}
}
}
else {
assert(!isLast, "Can't merge current value into a nested object");
target[key].mapValue.fields = merge(target[key].mapValue.fields, value, path, pos + 1);
return target;
}
}
const res = {};
for (const [key, value] of data) {
const path = key.toArray();
merge(res, value, path, 0);
}
return new DocumentSnapshot(ref, res);
}
/**
* True if the document exists.
*
* @type {boolean}
* @name DocumentSnapshot#exists
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Data: ${JSON.stringify(documentSnapshot.data())}`);
* }
* });
*/
get exists() {
return this._fieldsProto !== undefined;
}
/**
* A [DocumentReference]{@link DocumentReference} for the document
* stored in this snapshot.
*
* @type {DocumentReference}
* @name DocumentSnapshot#ref
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Found document at '${documentSnapshot.ref.path}'`);
* }
* });
*/
get ref() {
return this._ref;
}
/**
* The ID of the document for which this DocumentSnapshot contains data.
*
* @type {string}
* @name DocumentSnapshot#id
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Document found with name '${documentSnapshot.id}'`);
* }
* });
*/
get id() {
return this._ref.id;
}
/**
* The time the document was created. Undefined for documents that don't
* exist.
*
* @type {Timestamp|undefined}
* @name DocumentSnapshot#createTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* if (documentSnapshot.exists) {
* let createTime = documentSnapshot.createTime;
* console.log(`Document created at '${createTime.toDate()}'`);
* }
* });
*/
get createTime() {
return this._createTime;
}
/**
* The time the document was last updated (at the time the snapshot was
* generated). Undefined for documents that don't exist.
*
* @type {Timestamp|undefined}
* @name DocumentSnapshot#updateTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* if (documentSnapshot.exists) {
* let updateTime = documentSnapshot.updateTime;
* console.log(`Document updated at '${updateTime.toDate()}'`);
* }
* });
*/
get updateTime() {
return this._updateTime;
}
/**
* The time this snapshot was read.
*
* @type {Timestamp}
* @name DocumentSnapshot#readTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* let readTime = documentSnapshot.readTime;
* console.log(`Document read at '${readTime.toDate()}'`);
* });
*/
get readTime() {
if (this._readTime === undefined) {
throw new Error(`Called 'readTime' on a local document`);
}
return this._readTime;
}
/**
* Retrieves all fields in the document as an object. Returns 'undefined' if
* the document doesn't exist.
*
* @returns {T|undefined} An object containing all fields in the document or
* 'undefined' if the document doesn't exist.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* let data = documentSnapshot.data();
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
data() {
const fields = this._fieldsProto;
if (fields === undefined) {
return undefined;
}
const obj = {};
for (const prop of Object.keys(fields)) {
obj[prop] = this._serializer.decodeValue(fields[prop]);
}
return this.ref._converter.fromFirestore(obj);
}
/**
* Retrieves the field specified by `field`.
*
* @param {string|FieldPath} field The field path
* (e.g. 'foo' or 'foo.bar') to a specific field.
* @returns {*} The data at the specified field location or undefined if no
* such field exists.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ a: { b: 'c' }}).then(() => {
* return documentRef.get();
* }).then(documentSnapshot => {
* let field = documentSnapshot.get('a.b');
* console.log(`Retrieved field value: ${field}`);
* });
*/
// We deliberately use `any` in the external API to not impose type-checking
// on end users.
// tslint:disable-next-line no-any
get(field) {
// tslint:disable-line no-any
path_1.validateFieldPath('field', field);
const protoField = this.protoField(field);
if (protoField === undefined) {
return undefined;
}
return this._serializer.decodeValue(protoField);
}
/**
* Retrieves the field specified by 'fieldPath' in its Protobuf JS
* representation.
*
* @private
* @param field The path (e.g. 'foo' or 'foo.bar') to a specific field.
* @returns The Protobuf-encoded data at the specified field location or
* undefined if no such field exists.
*/
protoField(field) {
let fields = this._fieldsProto;
if (fields === undefined) {
return undefined;
}
const components = path_1.FieldPath.fromArgument(field).toArray();
while (components.length > 1) {
fields = fields[components.shift()];
if (!fields || !fields.mapValue) {
return undefined;
}
fields = fields.mapValue.fields;
}
return fields[components[0]];
}
/**
* Checks whether this DocumentSnapshot contains any fields.
*
* @private
* @return {boolean}
*/
get isEmpty() {
return this._fieldsProto === undefined || util_1.isEmpty(this._fieldsProto);
}
/**
* Convert a document snapshot to the Firestore 'Document' Protobuf.
*
* @private
* @returns The document in the format the API expects.
*/
toProto() {
return {
update: {
name: this._ref.formattedName,
fields: this._fieldsProto,
},
};
}
/**
* Returns true if the document's data and path in this `DocumentSnapshot` is
* equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `DocumentSnapshot` is equal to the provided
* value.
*/
isEqual(other) {
// Since the read time is different on every document read, we explicitly
// ignore all document metadata in this comparison.
return (this === other ||
(other instanceof DocumentSnapshot &&
this._ref.isEqual(other._ref) &&
deepEqual(this._fieldsProto, other._fieldsProto, { strict: true })));
}
}
exports.DocumentSnapshot = DocumentSnapshot;
/**
* A QueryDocumentSnapshot contains data read from a document in your
* Firestore database as part of a query. The document is guaranteed to exist
* and its data can be extracted with [data()]{@link QueryDocumentSnapshot#data}
* or [get()]{@link DocumentSnapshot#get} to get a specific field.
*
* A QueryDocumentSnapshot offers the same API surface as a
* {@link DocumentSnapshot}. Since query results contain only existing
* documents, the [exists]{@link DocumentSnapshot#exists} property will
* always be true and [data()]{@link QueryDocumentSnapshot#data} will never
* return 'undefined'.
*
* @class
* @extends DocumentSnapshot
*/
class QueryDocumentSnapshot extends DocumentSnapshot {
/**
* @hideconstructor
*
* @param ref The reference to the document.
* @param fieldsProto The fields of the Firestore `Document` Protobuf backing
* this document.
* @param readTime The time when this snapshot was read.
* @param createTime The time when the document was created.
* @param updateTime The time when the document was last updated.
*/
constructor(ref, fieldsProto, readTime, createTime, updateTime) {
super(ref, fieldsProto, readTime, createTime, updateTime);
}
/**
* The time the document was created.
*
* @type {Timestamp}
* @name QueryDocumentSnapshot#createTime
* @readonly
* @override
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(snapshot => {
* console.log(`Document created at '${snapshot.createTime.toDate()}'`);
* });
*/
get createTime() {
return super.createTime;
}
/**
* The time the document was last updated (at the time the snapshot was
* generated).
*
* @type {Timestamp}
* @name QueryDocumentSnapshot#updateTime
* @readonly
* @override
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(snapshot => {
* console.log(`Document updated at '${snapshot.updateTime.toDate()}'`);
* });
*/
get updateTime() {
return super.updateTime;
}
/**
* Retrieves all fields in the document as an object.
*
* @override
*
* @returns {T} An object containing all fields in the document.
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(documentSnapshot => {
* let data = documentSnapshot.data();
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
data() {
const data = super.data();
if (!data) {
throw new Error('The data in a QueryDocumentSnapshot should always exist.');
}
return data;
}
}
exports.QueryDocumentSnapshot = QueryDocumentSnapshot;
/**
* A Firestore Document Mask contains the field paths affected by an update.
*
* @class
* @private
*/
class DocumentMask {
/**
* @private
* @hideconstructor
*
* @param fieldPaths The field paths in this mask.
*/
constructor(fieldPaths) {
this._sortedPaths = fieldPaths;
this._sortedPaths.sort((a, b) => a.compareTo(b));
}
/**
* Creates a document mask with the field paths of a document.
*
* @private
* @param data A map with fields to modify. Only the keys are used to extract
* the document mask.
*/
static fromUpdateMap(data) {
const fieldPaths = [];
data.forEach((value, key) => {
if (!(value instanceof field_value_1.FieldTransform) || value.includeInDocumentMask) {
fieldPaths.push(path_1.FieldPath.fromArgument(key));
}
});
return new DocumentMask(fieldPaths);
}
/**
* Creates a document mask from an array of field paths.
*
* @private
* @param fieldMask A list of field paths.
*/
static fromFieldMask(fieldMask) {
const fieldPaths = [];
for (const fieldPath of fieldMask) {
fieldPaths.push(path_1.FieldPath.fromArgument(fieldPath));
}
return new DocumentMask(fieldPaths);
}
/**
* Creates a document mask with the field names of a document.
*
* @private
* @param data An object with fields to modify. Only the keys are used to
* extract the document mask.
*/
static fromObject(data) {
const fieldPaths = [];
function extractFieldPaths(currentData, currentPath) {
let isEmpty = true;
for (const key of Object.keys(currentData)) {
isEmpty = false;
// We don't split on dots since fromObject is called with
// DocumentData.
const childSegment = new path_1.FieldPath(key);
const childPath = currentPath
? currentPath.append(childSegment)
: childSegment;
const value = currentData[key];
if (value instanceof field_value_1.FieldTransform) {
if (value.includeInDocumentMask) {
fieldPaths.push(childPath);
}
}
else if (util_1.isPlainObject(value)) {
extractFieldPaths(value, childPath);
}
else {
fieldPaths.push(childPath);
}
}
// Add a field path for an explicitly updated empty map.
if (currentPath && isEmpty) {
fieldPaths.push(currentPath);
}
}
extractFieldPaths(data);
return new DocumentMask(fieldPaths);
}
/**
* Returns true if this document mask contains no fields.
*
* @private
* @return {boolean} Whether this document mask is empty.
*/
get isEmpty() {
return this._sortedPaths.length === 0;
}
/**
* Removes the specified values from a sorted field path array.
*
* @private
* @param input A sorted array of FieldPaths.
* @param values An array of FieldPaths to remove.
*/
static removeFromSortedArray(input, values) {
for (let i = 0; i < input.length;) {
let removed = false;
for (const fieldPath of values) {
if (input[i].isEqual(fieldPath)) {
input.splice(i, 1);
removed = true;
break;
}
}
if (!removed) {
++i;
}
}
}
/**
* Removes the field path specified in 'fieldPaths' from this document mask.
*
* @private
* @param fieldPaths An array of FieldPaths.
*/
removeFields(fieldPaths) {
DocumentMask.removeFromSortedArray(this._sortedPaths, fieldPaths);
}
/**
* Returns whether this document mask contains 'fieldPath'.
*
* @private
* @param fieldPath The field path to test.
* @return Whether this document mask contains 'fieldPath'.
*/
contains(fieldPath) {
for (const sortedPath of this._sortedPaths) {
const cmp = sortedPath.compareTo(fieldPath);
if (cmp === 0) {
return true;
}
else if (cmp > 0) {
return false;
}
}
return false;
}
/**
* Removes all properties from 'data' that are not contained in this document
* mask.
*
* @private
* @param data An object to filter.
* @return A shallow copy of the object filtered by this document mask.
*/
applyTo(data) {
/*!
* Applies this DocumentMask to 'data' and computes the list of field paths
* that were specified in the mask but are not present in 'data'.
*/
const applyDocumentMask = (data) => {
const remainingPaths = this._sortedPaths.slice(0);
const processObject = (currentData, currentPath) => {
let result = null;
Object.keys(currentData).forEach(key => {
const childPath = currentPath
? currentPath.append(key)
: new path_1.FieldPath(key);
if (this.contains(childPath)) {
DocumentMask.removeFromSortedArray(remainingPaths, [childPath]);
result = result || {};
result[key] = currentData[key];
}
else if (util_1.isObject(currentData[key])) {
const childObject = processObject(currentData[key], childPath);
if (childObject) {
result = result || {};
result[key] = childObject;
}
}
});
return result;
};
// processObject() returns 'null' if the DocumentMask is empty.
const filteredData = processObject(data) || {};
return {
filteredData,
remainingPaths,
};
};
const result = applyDocumentMask(data);
if (result.remainingPaths.length !== 0) {
throw new Error(`Input data is missing for field "${result.remainingPaths[0]}".`);
}
return result.filteredData;
}
/**
* Converts a document mask to the Firestore 'DocumentMask' Proto.
*
* @private
* @returns A Firestore 'DocumentMask' Proto.
*/
toProto() {
if (this.isEmpty) {
return {};
}
const encodedPaths = [];
for (const fieldPath of this._sortedPaths) {
encodedPaths.push(fieldPath.formattedName);
}
return {
fieldPaths: encodedPaths,
};
}
}
exports.DocumentMask = DocumentMask;
/**
* A Firestore Document Transform.
*
* A DocumentTransform contains pending server-side transforms and their
* corresponding field paths.
*
* @private
* @class
*/
class DocumentTransform {
/**
* @private
* @hideconstructor
*
* @param ref The DocumentReference for this transform.
* @param transforms A Map of FieldPaths to FieldTransforms.
*/
constructor(ref, transforms) {
this.ref = ref;
this.transforms = transforms;
}
/**
* Generates a DocumentTransform from a JavaScript object.
*
* @private
* @param ref The `DocumentReference` to use for the DocumentTransform.
* @param obj The object to extract the transformations from.
* @returns The Document Transform.
*/
static fromObject(ref, obj) {
const updateMap = new Map();
for (const prop of Object.keys(obj)) {
updateMap.set(new path_1.FieldPath(prop), obj[prop]);
}
return DocumentTransform.fromUpdateMap(ref, updateMap);
}
/**
* Generates a DocumentTransform from an Update Map.
*
* @private
* @param ref The `DocumentReference` to use for the DocumentTransform.
* @param data The update data to extract the transformations from.
* @returns The Document Transform.
*/
static fromUpdateMap(ref, data) {
const transforms = new Map();
function encode_(val, path, allowTransforms) {
if (val instanceof field_value_1.FieldTransform && val.includeInDocumentTransform) {
if (allowTransforms) {
transforms.set(path, val);
}
else {
throw new Error(`${val.methodName}() is not supported inside of array values.`);
}
}
else if (Array.isArray(val)) {
for (let i = 0; i < val.length; ++i) {
// We need to verify that no array value contains a document transform
encode_(val[i], path.append(String(i)), false);
}
}
else if (util_1.isPlainObject(val)) {
for (const prop of Object.keys(val)) {
encode_(val[prop], path.append(new path_1.FieldPath(prop)), allowTransforms);
}
}
}
data.forEach((value, key) => {
encode_(value, path_1.FieldPath.fromArgument(key), true);
});
return new DocumentTransform(ref, transforms);
}
/**
* Whether this DocumentTransform contains any actionable transformations.
*
* @private
*/
get isEmpty() {
return this.transforms.size === 0;
}
/**
* Returns the array of fields in this DocumentTransform.
*
* @private
*/
get fields() {
return Array.from(this.transforms.keys());
}
/**
* Validates the user provided field values in this document transform.
* @private
*/
validate() {
this.transforms.forEach(transform => transform.validate());
}
/**
* Converts a document transform to the Firestore 'DocumentTransform' Proto.
*
* @private
* @param serializer The Firestore serializer
* @returns A Firestore 'DocumentTransform' Proto or 'null' if this transform
* is empty.
*/
toProto(serializer) {
if (this.isEmpty) {
return null;
}
const fieldTransforms = [];
for (const [path, transform] of this.transforms) {
fieldTransforms.push(transform.toProto(serializer, path));
}
return {
transform: {
document: this.ref.formattedName,
fieldTransforms,
},
};
}
}
exports.DocumentTransform = DocumentTransform;
/**
* A Firestore Precondition encapsulates options for database writes.
*
* @private
* @class
*/
class Precondition {
/**
* @private
* @hideconstructor
*
* @param options.exists - Whether the referenced document should exist in
* Firestore,
* @param options.lastUpdateTime - The last update time of the referenced
* document in Firestore.
* @param options
*/
constructor(options) {
if (options !== undefined) {
this._exists = options.exists;
this._lastUpdateTime = options.lastUpdateTime;
}
}
/**
* Generates the Protobuf `Preconditon` object for this precondition.
*
* @private
* @returns The `Preconditon` Protobuf object or 'null' if there are no
* preconditions.
*/
toProto() {
if (this.isEmpty) {
return null;
}
const proto = {};
if (this._lastUpdateTime !== undefined) {
const valueProto = this._lastUpdateTime.toProto();
proto.updateTime = valueProto.timestampValue;
}
else {
proto.exists = this._exists;
}
return proto;
}
/**
* Whether this DocumentTransform contains any enforcement.
*
* @private
*/
get isEmpty() {
return this._exists === undefined && !this._lastUpdateTime;
}
}
exports.Precondition = Precondition;
//# sourceMappingURL=document.js.map

View File

@ -0,0 +1,229 @@
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as proto from '../protos/firestore_v1_proto_api';
import { FieldPath } from './path';
import { Serializer } from './serializer';
import api = proto.google.firestore.v1;
/**
* Sentinel values that can be used when writing documents with set(), create()
* or update().
*
* @class
*/
export declare class FieldValue {
/**
* @hideconstructor
*/
constructor();
/**
* Returns a sentinel for use with update() or set() with {merge:true} to mark
* a field for deletion.
*
* @returns {FieldValue} The sentinel value to use in your objects.
*
* @example
* let documentRef = firestore.doc('col/doc');
* let data = { a: 'b', c: 'd' };
*
* documentRef.set(data).then(() => {
* return documentRef.update({a: Firestore.FieldValue.delete()});
* }).then(() => {
* // Document now only contains { c: 'd' }
* });
*/
static delete(): FieldValue;
/**
* Returns a sentinel used with set(), create() or update() to include a
* server-generated timestamp in the written data.
*
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({
* time: Firestore.FieldValue.serverTimestamp()
* }).then(() => {
* return documentRef.get();
* }).then(doc => {
* console.log(`Server time set to ${doc.get('time')}`);
* });
*/
static serverTimestamp(): FieldValue;
/**
* Returns a special value that can be used with set(), create() or update()
* that tells the server to increment the the field's current value by the
* given value.
*
* If either current field value or the operand uses floating point
* precision, both values will be interpreted as floating point numbers and
* all arithmetic will follow IEEE 754 semantics. Otherwise, integer
* precision is kept and the result is capped between -2^63 and 2^63-1.
*
* If the current field value is not of type 'number', or if the field does
* not yet exist, the transformation will set the field to the given value.
*
* @param {number} n The value to increment by.
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update(
* 'counter', Firestore.FieldValue.increment(1)
* ).then(() => {
* return documentRef.get();
* }).then(doc => {
* // doc.get('counter') was incremented
* });
*/
static increment(n: number): FieldValue;
/**
* Returns a special value that can be used with set(), create() or update()
* that tells the server to union the given elements with any array value that
* already exists on the server. Each specified element that doesn't already
* exist in the array will be added to the end. If the field being modified is
* not already an array it will be overwritten with an array containing
* exactly the specified elements.
*
* @param {...*} elements The elements to union into the array.
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update(
* 'array', Firestore.FieldValue.arrayUnion('foo')
* ).then(() => {
* return documentRef.get();
* }).then(doc => {
* // doc.get('array') contains field 'foo'
* });
*/
static arrayUnion(...elements: unknown[]): FieldValue;
/**
* Returns a special value that can be used with set(), create() or update()
* that tells the server to remove the given elements from any array value
* that already exists on the server. All instances of each element specified
* will be removed from the array. If the field being modified is not already
* an array it will be overwritten with an empty array.
*
* @param {...*} elements The elements to remove from the array.
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update(
* 'array', Firestore.FieldValue.arrayRemove('foo')
* ).then(() => {
* return documentRef.get();
* }).then(doc => {
* // doc.get('array') no longer contains field 'foo'
* });
*/
static arrayRemove(...elements: unknown[]): FieldValue;
/**
* Returns true if this `FieldValue` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `FieldValue` is equal to the provided value.
*
* @example
* let fieldValues = [
* Firestore.FieldValue.increment(-1.0),
* Firestore.FieldValue.increment(-1),
* Firestore.FieldValue.increment(-0.0),
* Firestore.FieldValue.increment(-0),
* Firestore.FieldValue.increment(0),
* Firestore.FieldValue.increment(0.0),
* Firestore.FieldValue.increment(1),
* Firestore.FieldValue.increment(1.0)
* ];
*
* let equal = 0;
* for (let i = 0; i < fieldValues.length; ++i) {
* for (let j = i + 1; j < fieldValues.length; ++j) {
* if (fieldValues[i].isEqual(fieldValues[j])) {
* ++equal;
* }
* }
* }
* console.log(`Found ${equal} equalities.`);
*/
isEqual(other: FieldValue): boolean;
}
/**
* An internal interface shared by all field transforms.
*
* A 'FieldTransform` subclass should implement '.includeInDocumentMask',
* '.includeInDocumentTransform' and 'toProto' (if '.includeInDocumentTransform'
* is 'true').
*
* @private
* @abstract
*/
export declare abstract class FieldTransform extends FieldValue {
/** Whether this FieldTransform should be included in the document mask. */
abstract readonly includeInDocumentMask: boolean;
/**
* Whether this FieldTransform should be included in the list of document
* transforms.
*/
abstract readonly includeInDocumentTransform: boolean;
/** The method name used to obtain the field transform. */
abstract readonly methodName: string;
/** Performs input validation on the values of this field transform. */
abstract validate(): void;
/***
* The proto representation for this field transform.
*
* @param serializer The Firestore serializer.
* @param fieldPath The field path to apply this transformation to.
* @return The 'FieldTransform' proto message.
*/
abstract toProto(serializer: Serializer, fieldPath: FieldPath): api.DocumentTransform.IFieldTransform;
}
/**
* A transform that deletes a field from a Firestore document.
*
* @private
*/
export declare class DeleteTransform extends FieldTransform {
/**
* Sentinel value for a field delete.
* @private
*/
static DELETE_SENTINEL: DeleteTransform;
private constructor();
/**
* Deletes are included in document masks.
* @private
*/
readonly includeInDocumentMask: true;
/**
* Deletes are are omitted from document transforms.
* @private
*/
readonly includeInDocumentTransform: false;
readonly methodName: string;
validate(): void;
toProto(serializer: Serializer, fieldPath: FieldPath): never;
}

View File

@ -0,0 +1,429 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const deepEqual = require('deep-equal');
const serializer_1 = require("./serializer");
const validate_1 = require("./validate");
/**
* Sentinel values that can be used when writing documents with set(), create()
* or update().
*
* @class
*/
class FieldValue {
/**
* @hideconstructor
*/
constructor() { }
/**
* Returns a sentinel for use with update() or set() with {merge:true} to mark
* a field for deletion.
*
* @returns {FieldValue} The sentinel value to use in your objects.
*
* @example
* let documentRef = firestore.doc('col/doc');
* let data = { a: 'b', c: 'd' };
*
* documentRef.set(data).then(() => {
* return documentRef.update({a: Firestore.FieldValue.delete()});
* }).then(() => {
* // Document now only contains { c: 'd' }
* });
*/
static delete() {
return DeleteTransform.DELETE_SENTINEL;
}
/**
* Returns a sentinel used with set(), create() or update() to include a
* server-generated timestamp in the written data.
*
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({
* time: Firestore.FieldValue.serverTimestamp()
* }).then(() => {
* return documentRef.get();
* }).then(doc => {
* console.log(`Server time set to ${doc.get('time')}`);
* });
*/
static serverTimestamp() {
return ServerTimestampTransform.SERVER_TIMESTAMP_SENTINEL;
}
/**
* Returns a special value that can be used with set(), create() or update()
* that tells the server to increment the the field's current value by the
* given value.
*
* If either current field value or the operand uses floating point
* precision, both values will be interpreted as floating point numbers and
* all arithmetic will follow IEEE 754 semantics. Otherwise, integer
* precision is kept and the result is capped between -2^63 and 2^63-1.
*
* If the current field value is not of type 'number', or if the field does
* not yet exist, the transformation will set the field to the given value.
*
* @param {number} n The value to increment by.
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update(
* 'counter', Firestore.FieldValue.increment(1)
* ).then(() => {
* return documentRef.get();
* }).then(doc => {
* // doc.get('counter') was incremented
* });
*/
static increment(n) {
validate_1.validateMinNumberOfArguments('FieldValue.increment', arguments, 1);
return new NumericIncrementTransform(n);
}
/**
* Returns a special value that can be used with set(), create() or update()
* that tells the server to union the given elements with any array value that
* already exists on the server. Each specified element that doesn't already
* exist in the array will be added to the end. If the field being modified is
* not already an array it will be overwritten with an array containing
* exactly the specified elements.
*
* @param {...*} elements The elements to union into the array.
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update(
* 'array', Firestore.FieldValue.arrayUnion('foo')
* ).then(() => {
* return documentRef.get();
* }).then(doc => {
* // doc.get('array') contains field 'foo'
* });
*/
static arrayUnion(...elements) {
validate_1.validateMinNumberOfArguments('FieldValue.arrayUnion', arguments, 1);
return new ArrayUnionTransform(elements);
}
/**
* Returns a special value that can be used with set(), create() or update()
* that tells the server to remove the given elements from any array value
* that already exists on the server. All instances of each element specified
* will be removed from the array. If the field being modified is not already
* an array it will be overwritten with an empty array.
*
* @param {...*} elements The elements to remove from the array.
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update(
* 'array', Firestore.FieldValue.arrayRemove('foo')
* ).then(() => {
* return documentRef.get();
* }).then(doc => {
* // doc.get('array') no longer contains field 'foo'
* });
*/
static arrayRemove(...elements) {
validate_1.validateMinNumberOfArguments('FieldValue.arrayRemove', arguments, 1);
return new ArrayRemoveTransform(elements);
}
/**
* Returns true if this `FieldValue` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `FieldValue` is equal to the provided value.
*
* @example
* let fieldValues = [
* Firestore.FieldValue.increment(-1.0),
* Firestore.FieldValue.increment(-1),
* Firestore.FieldValue.increment(-0.0),
* Firestore.FieldValue.increment(-0),
* Firestore.FieldValue.increment(0),
* Firestore.FieldValue.increment(0.0),
* Firestore.FieldValue.increment(1),
* Firestore.FieldValue.increment(1.0)
* ];
*
* let equal = 0;
* for (let i = 0; i < fieldValues.length; ++i) {
* for (let j = i + 1; j < fieldValues.length; ++j) {
* if (fieldValues[i].isEqual(fieldValues[j])) {
* ++equal;
* }
* }
* }
* console.log(`Found ${equal} equalities.`);
*/
isEqual(other) {
return this === other;
}
}
exports.FieldValue = FieldValue;
/**
* An internal interface shared by all field transforms.
*
* A 'FieldTransform` subclass should implement '.includeInDocumentMask',
* '.includeInDocumentTransform' and 'toProto' (if '.includeInDocumentTransform'
* is 'true').
*
* @private
* @abstract
*/
class FieldTransform extends FieldValue {
}
exports.FieldTransform = FieldTransform;
/**
* A transform that deletes a field from a Firestore document.
*
* @private
*/
class DeleteTransform extends FieldTransform {
constructor() {
super();
}
/**
* Deletes are included in document masks.
* @private
*/
get includeInDocumentMask() {
return true;
}
/**
* Deletes are are omitted from document transforms.
* @private
*/
get includeInDocumentTransform() {
return false;
}
get methodName() {
return 'FieldValue.delete';
}
validate() { }
toProto(serializer, fieldPath) {
throw new Error('FieldValue.delete() should not be included in a FieldTransform');
}
}
exports.DeleteTransform = DeleteTransform;
/**
* Sentinel value for a field delete.
* @private
*/
DeleteTransform.DELETE_SENTINEL = new DeleteTransform();
/**
* A transform that sets a field to the Firestore server time.
*
* @private
*/
class ServerTimestampTransform extends FieldTransform {
constructor() {
super();
}
/**
* Server timestamps are omitted from document masks.
*
* @private
*/
get includeInDocumentMask() {
return false;
}
/**
* Server timestamps are included in document transforms.
*
* @private
*/
get includeInDocumentTransform() {
return true;
}
get methodName() {
return 'FieldValue.serverTimestamp';
}
validate() { }
toProto(serializer, fieldPath) {
return {
fieldPath: fieldPath.formattedName,
setToServerValue: 'REQUEST_TIME',
};
}
}
/**
* Sentinel value for a server timestamp.
*
* @private
*/
ServerTimestampTransform.SERVER_TIMESTAMP_SENTINEL = new ServerTimestampTransform();
/**
* Increments a field value on the backend.
*
* @private
*/
class NumericIncrementTransform extends FieldTransform {
constructor(operand) {
super();
this.operand = operand;
}
/**
* Numeric transforms are omitted from document masks.
*
* @private
*/
get includeInDocumentMask() {
return false;
}
/**
* Numeric transforms are included in document transforms.
*
* @private
*/
get includeInDocumentTransform() {
return true;
}
get methodName() {
return 'FieldValue.increment';
}
validate() {
validate_1.validateNumber('FieldValue.increment()', this.operand);
}
toProto(serializer, fieldPath) {
const encodedOperand = serializer.encodeValue(this.operand);
return { fieldPath: fieldPath.formattedName, increment: encodedOperand };
}
isEqual(other) {
return (this === other ||
(other instanceof NumericIncrementTransform &&
this.operand === other.operand));
}
}
/**
* Transforms an array value via a union operation.
*
* @private
*/
class ArrayUnionTransform extends FieldTransform {
constructor(elements) {
super();
this.elements = elements;
}
/**
* Array transforms are omitted from document masks.
* @private
*/
get includeInDocumentMask() {
return false;
}
/**
* Array transforms are included in document transforms.
* @private
*/
get includeInDocumentTransform() {
return true;
}
get methodName() {
return 'FieldValue.arrayUnion';
}
validate() {
for (let i = 0; i < this.elements.length; ++i) {
validateArrayElement(i, this.elements[i]);
}
}
toProto(serializer, fieldPath) {
const encodedElements = serializer.encodeValue(this.elements).arrayValue;
return {
fieldPath: fieldPath.formattedName,
appendMissingElements: encodedElements,
};
}
isEqual(other) {
return (this === other ||
(other instanceof ArrayUnionTransform &&
deepEqual(this.elements, other.elements, { strict: true })));
}
}
/**
* Transforms an array value via a remove operation.
*
* @private
*/
class ArrayRemoveTransform extends FieldTransform {
constructor(elements) {
super();
this.elements = elements;
}
/**
* Array transforms are omitted from document masks.
* @private
*/
get includeInDocumentMask() {
return false;
}
/**
* Array transforms are included in document transforms.
* @private
*/
get includeInDocumentTransform() {
return true;
}
get methodName() {
return 'FieldValue.arrayRemove';
}
validate() {
for (let i = 0; i < this.elements.length; ++i) {
validateArrayElement(i, this.elements[i]);
}
}
toProto(serializer, fieldPath) {
const encodedElements = serializer.encodeValue(this.elements).arrayValue;
return {
fieldPath: fieldPath.formattedName,
removeAllFromArray: encodedElements,
};
}
isEqual(other) {
return (this === other ||
(other instanceof ArrayRemoveTransform &&
deepEqual(this.elements, other.elements, { strict: true })));
}
}
/**
* Validates that `value` can be used as an element inside of an array. Certain
* field values (such as ServerTimestamps) are rejected.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The value to validate.
*/
function validateArrayElement(arg, value) {
serializer_1.validateUserInput(arg, value, 'array element',
/*path=*/ { allowDeletes: 'none', allowTransforms: false },
/*path=*/ undefined,
/*level=*/ 0,
/*inArray=*/ true);
}
//# sourceMappingURL=field-value.js.map

View File

@ -0,0 +1,78 @@
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { google } from '../protos/firestore_v1_proto_api';
import { Serializable } from './serializer';
import api = google.firestore.v1;
/**
* An immutable object representing a geographic location in Firestore. The
* location is represented as a latitude/longitude pair.
*
* @class
*/
export declare class GeoPoint implements Serializable {
private readonly _latitude;
private readonly _longitude;
/**
* Creates a [GeoPoint]{@link GeoPoint}.
*
* @param {number} latitude The latitude as a number between -90 and 90.
* @param {number} longitude The longitude as a number between -180 and 180.
*
* @example
* let data = {
* google: new Firestore.GeoPoint(37.422, 122.084)
* };
*
* firestore.doc('col/doc').set(data).then(() => {
* console.log(`Location is ${data.google.latitude}, ` +
* `${data.google.longitude}`);
* });
*/
constructor(latitude: number, longitude: number);
/**
* The latitude as a number between -90 and 90.
*
* @type {number}
* @name GeoPoint#latitude
* @readonly
*/
readonly latitude: number;
/**
* The longitude as a number between -180 and 180.
*
* @type {number}
* @name GeoPoint#longitude
* @readonly
*/
readonly longitude: number;
/**
* Returns true if this `GeoPoint` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `GeoPoint` is equal to the provided value.
*/
isEqual(other: GeoPoint): boolean;
/**
* Converts the GeoPoint to a google.type.LatLng proto.
* @private
*/
toProto(): api.IValue;
/**
* Converts a google.type.LatLng proto to its GeoPoint representation.
* @private
*/
static fromProto(proto: google.type.ILatLng): GeoPoint;
}

View File

@ -0,0 +1,101 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("./validate");
/**
* An immutable object representing a geographic location in Firestore. The
* location is represented as a latitude/longitude pair.
*
* @class
*/
class GeoPoint {
/**
* Creates a [GeoPoint]{@link GeoPoint}.
*
* @param {number} latitude The latitude as a number between -90 and 90.
* @param {number} longitude The longitude as a number between -180 and 180.
*
* @example
* let data = {
* google: new Firestore.GeoPoint(37.422, 122.084)
* };
*
* firestore.doc('col/doc').set(data).then(() => {
* console.log(`Location is ${data.google.latitude}, ` +
* `${data.google.longitude}`);
* });
*/
constructor(latitude, longitude) {
validate_1.validateNumber('latitude', latitude, { minValue: -90, maxValue: 90 });
validate_1.validateNumber('longitude', longitude, { minValue: -180, maxValue: 180 });
this._latitude = latitude;
this._longitude = longitude;
}
/**
* The latitude as a number between -90 and 90.
*
* @type {number}
* @name GeoPoint#latitude
* @readonly
*/
get latitude() {
return this._latitude;
}
/**
* The longitude as a number between -180 and 180.
*
* @type {number}
* @name GeoPoint#longitude
* @readonly
*/
get longitude() {
return this._longitude;
}
/**
* Returns true if this `GeoPoint` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `GeoPoint` is equal to the provided value.
*/
isEqual(other) {
return (this === other ||
(other instanceof GeoPoint &&
this.latitude === other.latitude &&
this.longitude === other.longitude));
}
/**
* Converts the GeoPoint to a google.type.LatLng proto.
* @private
*/
toProto() {
return {
geoPointValue: {
latitude: this.latitude,
longitude: this.longitude,
},
};
}
/**
* Converts a google.type.LatLng proto to its GeoPoint representation.
* @private
*/
static fromProto(proto) {
return new GeoPoint(proto.latitude || 0, proto.longitude || 0);
}
}
exports.GeoPoint = GeoPoint;
//# sourceMappingURL=geo-point.js.map

View File

@ -0,0 +1,549 @@
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference types="node" />
import { Duplex } from 'stream';
import { google } from '../protos/firestore_v1_proto_api';
import { DocumentSnapshot, QueryDocumentSnapshot } from './document';
import { FieldPath } from './path';
import { CollectionReference, Query } from './reference';
import { DocumentReference } from './reference';
import { Serializer } from './serializer';
import { Transaction } from './transaction';
import { FirestoreStreamingMethod, FirestoreUnaryMethod, ReadOptions, Settings } from './types';
import { WriteBatch } from './write-batch';
import api = google.firestore.v1;
export { CollectionReference, DocumentReference, QuerySnapshot, Query, } from './reference';
export { DocumentSnapshot, QueryDocumentSnapshot } from './document';
export { FieldValue } from './field-value';
export { WriteBatch, WriteResult } from './write-batch';
export { Transaction } from './transaction';
export { Timestamp } from './timestamp';
export { DocumentChange } from './document-change';
export { FieldPath } from './path';
export { GeoPoint } from './geo-point';
export { setLogFunction } from './logger';
export { FirestoreDataConverter, UpdateData, DocumentData, Settings, Precondition, SetOptions, } from './types';
/**
* Document data (e.g. for use with
* [set()]{@link DocumentReference#set}) consisting of fields mapped
* to values.
*
* @typedef {Object.<string, *>} DocumentData
*/
/**
* Update data (for use with [update]{@link DocumentReference#update})
* that contains paths (e.g. 'foo' or 'foo.baz') mapped to values. Fields that
* contain dots reference nested fields within the document.
*
* @typedef {Object.<string, *>} UpdateData
*/
/**
* An options object that configures conditional behavior of
* [update()]{@link DocumentReference#update} and
* [delete()]{@link DocumentReference#delete} calls in
* [DocumentReference]{@link DocumentReference},
* [WriteBatch]{@link WriteBatch}, and
* [Transaction]{@link Transaction}. Using Preconditions, these calls
* can be restricted to only apply to documents that match the specified
* conditions.
*
* @example
* const documentRef = firestore.doc('coll/doc');
*
* documentRef.get().then(snapshot => {
* const updateTime = snapshot.updateTime;
*
* console.log(`Deleting document at update time: ${updateTime.toDate()}`);
* return documentRef.delete({ lastUpdateTime: updateTime });
* });
*
* @property {string} lastUpdateTime The update time to enforce (specified as
* an ISO 8601 string).
* @typedef {Object} Precondition
*/
/**
* An options object that configures the behavior of
* [set()]{@link DocumentReference#set} calls in
* [DocumentReference]{@link DocumentReference},
* [WriteBatch]{@link WriteBatch}, and
* [Transaction]{@link Transaction}. These calls can be
* configured to perform granular merges instead of overwriting the target
* documents in their entirety by providing a SetOptions object with
* { merge : true }.
*
* @property {boolean} merge Changes the behavior of a set() call to only
* replace the values specified in its data argument. Fields omitted from the
* set() call remain untouched.
* @property {Array<(string|FieldPath)>} mergeFields Changes the behavior of
* set() calls to only replace the specified field paths. Any field path that is
* not specified is ignored and remains untouched.
* It is an error to pass a SetOptions object to a set() call that is missing a
* value for any of the fields specified here.
* @typedef {Object} SetOptions
*/
/**
* An options object that can be used to configure the behavior of
* [getAll()]{@link Firestore#getAll} calls. By providing a `fieldMask`, these
* calls can be configured to only return a subset of fields.
*
* @property {Array<(string|FieldPath)>} fieldMask Specifies the set of fields
* to return and reduces the amount of data transmitted by the backend.
* Adding a field mask does not filter results. Documents do not need to
* contain values for all the fields in the mask to be part of the result set.
* @typedef {Object} ReadOptions
*/
/**
* The Firestore client represents a Firestore Database and is the entry point
* for all Firestore operations.
*
* @see [Firestore Documentation]{@link https://firebase.google.com/docs/firestore/}
*
* @class
*
* @example <caption>Install the client library with <a
* href="https://www.npmjs.com/">npm</a>:</caption> npm install --save
* @google-cloud/firestore
*
* @example <caption>Import the client library</caption>
* var Firestore = require('@google-cloud/firestore');
*
* @example <caption>Create a client that uses <a
* href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application
* Default Credentials (ADC)</a>:</caption> var firestore = new Firestore();
*
* @example <caption>Create a client with <a
* href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit
* credentials</a>:</caption> var firestore = new Firestore({ projectId:
* 'your-project-id', keyFilename: '/path/to/keyfile.json'
* });
*
* @example <caption>include:samples/quickstart.js</caption>
* region_tag:firestore_quickstart
* Full quickstart example:
*/
export declare class Firestore {
/**
* A client pool to distribute requests over multiple GAPIC clients in order
* to work around a connection limit of 100 concurrent requests per client.
* @private
*/
private _clientPool;
/**
* The configuration options for the GAPIC client.
* @private
*/
private _settings;
/**
* Settings for the exponential backoff used by the streaming endpoints.
* @private
*/
private _backoffSettings;
/**
* Whether the initialization settings can still be changed by invoking
* `settings()`.
* @private
*/
private _settingsFrozen;
/**
* The serializer to use for the Protobuf transformation.
* @private
*/
_serializer: Serializer | null;
/**
* The project ID for this client.
*
* The project ID is auto-detected during the first request unless a project
* ID is passed to the constructor (or provided via `.settings()`).
* @private
*/
private _projectId;
/** @private */
_preferTransactions: boolean;
/** @private */
_lastSuccessfulRequest: number;
/**
* @param {Object=} settings [Configuration object](#/docs).
* @param {string=} settings.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. Can be omitted in
* environments that support
* {@link https://cloud.google.com/docs/authentication Application Default
* Credentials}
* @param {string=} settings.keyFilename Local file containing the Service
* Account credentials as downloaded from the Google Developers Console. Can
* be omitted in environments that support
* {@link https://cloud.google.com/docs/authentication Application Default
* Credentials}. To configure Firestore with custom credentials, use
* `settings.credentials` and provide the `client_email` and `private_key` of
* your service account.
* @param {{client_email:string=, private_key:string=}=} settings.credentials
* The `client_email` and `private_key` properties of the service account
* to use with your Firestore project. Can be omitted in environments that
* support {@link https://cloud.google.com/docs/authentication Application
* Default Credentials}. If your credentials are stored in a JSON file, you
* can specify a `keyFilename` instead.
* @param {string=} settings.host The host to connect to.
* @param {boolean=} settings.ssl Whether to use SSL when connecting.
* @param {number=} settings.maxIdleChannels The maximum number of idle GRPC
* channels to keep. A smaller number of idle channels reduces memory usage
* but increases request latency for clients with fluctuating request rates.
* If set to 0, shuts down all GRPC channels when the client becomes idle.
* Defaults to 1.
*/
constructor(settings?: Settings);
/**
* Specifies custom settings to be used to configure the `Firestore`
* instance. Can only be invoked once and before any other Firestore method.
*
* If settings are provided via both `settings()` and the `Firestore`
* constructor, both settings objects are merged and any settings provided via
* `settings()` take precedence.
*
* @param {object} settings The settings to use for all Firestore operations.
*/
settings(settings: Settings): void;
private validateAndApplySettings;
/**
* Returns the Project ID for this Firestore instance. Validates that
* `initializeIfNeeded()` was called before.
*
* @private
*/
readonly projectId: string;
/**
* Returns the root path of the database. Validates that
* `initializeIfNeeded()` was called before.
*
* @private
*/
readonly formattedName: string;
/**
* Gets a [DocumentReference]{@link DocumentReference} instance that
* refers to the document at the specified path.
*
* @param {string} documentPath A slash-separated path to a document.
* @returns {DocumentReference} The
* [DocumentReference]{@link DocumentReference} instance.
*
* @example
* let documentRef = firestore.doc('collection/document');
* console.log(`Path of document is ${documentRef.path}`);
*/
doc(documentPath: string): DocumentReference;
/**
* Gets a [CollectionReference]{@link CollectionReference} instance
* that refers to the collection at the specified path.
*
* @param {string} collectionPath A slash-separated path to a collection.
* @returns {CollectionReference} The
* [CollectionReference]{@link CollectionReference} instance.
*
* @example
* let collectionRef = firestore.collection('collection');
*
* // Add a document with an auto-generated ID.
* collectionRef.add({foo: 'bar'}).then((documentRef) => {
* console.log(`Added document at ${documentRef.path})`);
* });
*/
collection(collectionPath: string): CollectionReference;
/**
* Creates and returns a new Query that includes all documents in the
* database that are contained in a collection or subcollection with the
* given collectionId.
*
* @param {string} collectionId Identifies the collections to query over.
* Every collection or subcollection with this ID as the last segment of its
* path will be included. Cannot contain a slash.
* @returns {Query} The created Query.
*
* @example
* let docA = firestore.doc('mygroup/docA').set({foo: 'bar'});
* let docB = firestore.doc('abc/def/mygroup/docB').set({foo: 'bar'});
*
* Promise.all([docA, docB]).then(() => {
* let query = firestore.collectionGroup('mygroup');
* query = query.where('foo', '==', 'bar');
* return query.get().then(snapshot => {
* console.log(`Found ${snapshot.size} documents.`);
* });
* });
*/
collectionGroup(collectionId: string): Query;
/**
* Creates a [WriteBatch]{@link WriteBatch}, used for performing
* multiple writes as a single atomic operation.
*
* @returns {WriteBatch} A WriteBatch that operates on this Firestore
* client.
*
* @example
* let writeBatch = firestore.batch();
*
* // Add two documents in an atomic batch.
* let data = { foo: 'bar' };
* writeBatch.set(firestore.doc('col/doc1'), data);
* writeBatch.set(firestore.doc('col/doc2'), data);
*
* writeBatch.commit().then(res => {
* console.log(`Added document at ${res.writeResults[0].updateTime}`);
* });
*/
batch(): WriteBatch;
/**
* Creates a [DocumentSnapshot]{@link DocumentSnapshot} or a
* [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} from a
* `firestore.v1.Document` proto (or from a resource name for missing
* documents).
*
* This API is used by Google Cloud Functions and can be called with both
* 'Proto3 JSON' and 'Protobuf JS' encoded data.
*
* @private
* @param documentOrName The Firestore 'Document' proto or the resource name
* of a missing document.
* @param readTime A 'Timestamp' proto indicating the time this document was
* read.
* @param encoding One of 'json' or 'protobufJS'. Applies to both the
* 'document' Proto and 'readTime'. Defaults to 'protobufJS'.
* @returns A QueryDocumentSnapshot for existing documents, otherwise a
* DocumentSnapshot.
*/
snapshot_(documentName: string, readTime?: google.protobuf.ITimestamp, encoding?: 'protobufJS'): DocumentSnapshot;
snapshot_(documentName: string, readTime: string, encoding: 'json'): DocumentSnapshot;
snapshot_(document: api.IDocument, readTime: google.protobuf.ITimestamp, encoding?: 'protobufJS'): QueryDocumentSnapshot;
snapshot_(document: {
[k: string]: unknown;
}, readTime: string, encoding: 'json'): QueryDocumentSnapshot;
/**
* Executes the given updateFunction and commits the changes applied within
* the transaction.
*
* You can use the transaction object passed to 'updateFunction' to read and
* modify Firestore documents under lock. Transactions are committed once
* 'updateFunction' resolves and attempted up to five times on failure.
*
* @param {function(Transaction)} updateFunction The function to execute
* within the transaction context.
* @param {object=} transactionOptions Transaction options.
* @param {number=} transactionOptions.maxAttempts - The maximum number of
* attempts for this transaction.
* @returns {Promise} If the transaction completed successfully or was
* explicitly aborted (by the updateFunction returning a failed Promise), the
* Promise returned by the updateFunction will be returned here. Else if the
* transaction failed, a rejected Promise with the corresponding failure
* error will be returned.
*
* @example
* let counterTransaction = firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (doc.exists) {
* let count = doc.get('count') || 0;
* if (count > 10) {
* return Promise.reject('Reached maximum count');
* }
* transaction.update(documentRef, { count: ++count });
* return Promise.resolve(count);
* }
*
* transaction.create(documentRef, { count: 1 });
* return Promise.resolve(1);
* });
* });
*
* counterTransaction.then(res => {
* console.log(`Count updated to ${res}`);
* });
*/
runTransaction<T>(updateFunction: (transaction: Transaction) => Promise<T>, transactionOptions?: {
maxAttempts?: number;
}): Promise<T>;
/**
* Fetches the root collections that are associated with this Firestore
* database.
*
* @returns {Promise.<Array.<CollectionReference>>} A Promise that resolves
* with an array of CollectionReferences.
*
* @example
* firestore.listCollections().then(collections => {
* for (let collection of collections) {
* console.log(`Found collection with id: ${collection.id}`);
* }
* });
*/
listCollections(): Promise<CollectionReference[]>;
/**
* Retrieves multiple documents from Firestore.
*
* The first argument is required and must be of type `DocumentReference`
* followed by any additional `DocumentReference` documents. If used, the
* optional `ReadOptions` must be the last argument.
*
* @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The
* `DocumentReferences` to receive, followed by an optional field mask.
* @returns {Promise<Array.<DocumentSnapshot>>} A Promise that
* contains an array with the resulting document snapshots.
*
* @example
* let docRef1 = firestore.doc('col/doc1');
* let docRef2 = firestore.doc('col/doc2');
*
* firestore.getAll(docRef1, docRef2, { fieldMask: ['user'] }).then(docs => {
* console.log(`First document: ${JSON.stringify(docs[0])}`);
* console.log(`Second document: ${JSON.stringify(docs[1])}`);
* });
*/
getAll<T>(...documentRefsOrReadOptions: Array<DocumentReference<T> | ReadOptions>): Promise<Array<DocumentSnapshot<T>>>;
/**
* Internal method to retrieve multiple documents from Firestore, optionally
* as part of a transaction.
*
* @private
* @param docRefs The documents to receive.
* @param fieldMask An optional field mask to apply to this read.
* @param requestTag A unique client-assigned identifier for this request.
* @param transactionId The transaction ID to use for this read.
* @returns A Promise that contains an array with the resulting documents.
*/
getAll_<T>(docRefs: Array<DocumentReference<T>>, fieldMask: FieldPath[] | null, requestTag: string, transactionId?: Uint8Array): Promise<Array<DocumentSnapshot<T>>>;
/**
* Terminates the Firestore client and closes all open streams.
*
* @return A Promise that resolves when the client is terminated.
*/
terminate(): Promise<void>;
/**
* Initializes the client if it is not already initialized. All methods in the
* SDK can be used after this method completes.
*
* @private
* @param requestTag A unique client-assigned identifier that caused this
* initialization.
* @return A Promise that resolves when the client is initialized.
*/
initializeIfNeeded(requestTag: string): Promise<void>;
/**
* Returns GAX call options that set the cloud resource header.
* @private
*/
private createCallOptions;
/**
* A function returning a Promise that can be retried.
*
* @private
* @callback retryFunction
* @returns {Promise} A Promise indicating the function's success.
*/
/**
* Helper method that retries failed Promises.
*
* If 'delayMs' is specified, waits 'delayMs' between invocations. Otherwise,
* schedules the first attempt immediately, and then waits 100 milliseconds
* for further attempts.
*
* @private
* @param methodName Name of the Veneer API endpoint that takes a request
* and GAX options.
* @param requestTag A unique client-assigned identifier for this request.
* @param func Method returning a Promise than can be retried.
* @returns - A Promise with the function's result if successful within
* `attemptsRemaining`. Otherwise, returns the last rejected Promise.
*/
private _retry;
/**
* Waits for the provided stream to become active and returns a paused but
* healthy stream. If an error occurs before the first byte is read, the
* method rejects the returned Promise.
*
* @private
* @param backendStream The Node stream to monitor.
* @param lifetime A Promise that resolves when the stream receives an 'end',
* 'close' or 'finish' message.
* @param requestTag A unique client-assigned identifier for this request.
* @param request If specified, the request that should be written to the
* stream after opening.
* @returns A guaranteed healthy stream that should be used instead of
* `backendStream`.
*/
private _initializeStream;
/**
* A funnel for all non-streaming API requests, assigning a project ID where
* necessary within the request options.
*
* @private
* @param methodName Name of the Veneer API endpoint that takes a request
* and GAX options.
* @param request The Protobuf request to send.
* @param requestTag A unique client-assigned identifier for this request.
* @returns A Promise with the request result.
*/
request<Req, Resp>(methodName: FirestoreUnaryMethod, request: Req, requestTag: string): Promise<Resp>;
/**
* A funnel for streaming API requests, assigning a project ID where necessary
* within the request options.
*
* The stream is returned in paused state and needs to be resumed once all
* listeners are attached.
*
* @private
* @param methodName Name of the streaming Veneer API endpoint that
* takes a request and GAX options.
* @param request The Protobuf request to send.
* @param requestTag A unique client-assigned identifier for this request.
* @returns A Promise with the resulting read-only stream.
*/
requestStream(methodName: FirestoreStreamingMethod, request: {}, requestTag: string): Promise<Duplex>;
}
/**
* A logging function that takes a single string.
*
* @callback Firestore~logFunction
* @param {string} Log message
*/
/**
* The default export of the `@google-cloud/firestore` package is the
* {@link Firestore} class.
*
* See {@link Firestore} and {@link ClientConfig} for client methods and
* configuration options.
*
* @module {Firestore} @google-cloud/firestore
* @alias nodejs-firestore
*
* @example <caption>Install the client library with <a
* href="https://www.npmjs.com/">npm</a>:</caption> npm install --save
* @google-cloud/firestore
*
* @example <caption>Import the client library</caption>
* var Firestore = require('@google-cloud/firestore');
*
* @example <caption>Create a client that uses <a
* href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application
* Default Credentials (ADC)</a>:</caption> var firestore = new Firestore();
*
* @example <caption>Create a client with <a
* href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit
* credentials</a>:</caption> var firestore = new Firestore({ projectId:
* 'your-project-id', keyFilename: '/path/to/keyfile.json'
* });
*
* @example <caption>include:samples/quickstart.js</caption>
* region_tag:firestore_quickstart
* Full quickstart example:
*/
export default Firestore;

1029
node_modules/@google-cloud/firestore/build/src/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Log function to use for debug output. By default, we don't perform any
* logging.
*
* @private
*/
export declare function logger(methodName: string, requestTag: string | null, logMessage: string, ...additionalArgs: unknown[]): void;
/**
* Sets or disables the log function for all active Firestore instances.
*
* @param logger A log function that takes a message (such as `console.log`) or
* `null` to turn off logging.
*/
export declare function setLogFunction(logger: ((msg: string) => void) | null): void;
/**
* Sets the library version to be used in log messages.
*
* @private
*/
export declare function setLibVersion(version: string): void;

View File

@ -0,0 +1,60 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const util = require("util");
const validate_1 = require("./validate");
/*! The Firestore library version */
let libVersion;
/*! The external function used to emit logs. */
let logFunction = null;
/**
* Log function to use for debug output. By default, we don't perform any
* logging.
*
* @private
*/
function logger(methodName, requestTag, logMessage, ...additionalArgs) {
requestTag = requestTag || '#####';
if (logFunction) {
const formattedMessage = util.format(logMessage, ...additionalArgs);
const time = new Date().toISOString();
logFunction(`Firestore (${libVersion}) ${time} ${requestTag} [${methodName}]: ` +
formattedMessage);
}
}
exports.logger = logger;
/**
* Sets or disables the log function for all active Firestore instances.
*
* @param logger A log function that takes a message (such as `console.log`) or
* `null` to turn off logging.
*/
function setLogFunction(logger) {
validate_1.validateFunction('logger', logger);
logFunction = logger;
}
exports.setLogFunction = setLogFunction;
/**
* Sets the library version to be used in log messages.
*
* @private
*/
function setLibVersion(version) {
libVersion = version;
}
exports.setLibVersion = setLibVersion;
//# sourceMappingURL=logger.js.map

View File

@ -0,0 +1,25 @@
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { google } from '../protos/firestore_v1_proto_api';
import api = google.firestore.v1;
/*!
* @private
*/
export declare function primitiveComparator(left: string | boolean | number, right: string | boolean | number): number;
/*!
* @private
*/
export declare function compare(left: api.IValue, right: api.IValue): number;

230
node_modules/@google-cloud/firestore/build/src/order.js generated vendored Normal file
View File

@ -0,0 +1,230 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const convert_1 = require("./convert");
const path_1 = require("./path");
/*!
* The type order as defined by the backend.
*/
var TypeOrder;
(function (TypeOrder) {
TypeOrder[TypeOrder["NULL"] = 0] = "NULL";
TypeOrder[TypeOrder["BOOLEAN"] = 1] = "BOOLEAN";
TypeOrder[TypeOrder["NUMBER"] = 2] = "NUMBER";
TypeOrder[TypeOrder["TIMESTAMP"] = 3] = "TIMESTAMP";
TypeOrder[TypeOrder["STRING"] = 4] = "STRING";
TypeOrder[TypeOrder["BLOB"] = 5] = "BLOB";
TypeOrder[TypeOrder["REF"] = 6] = "REF";
TypeOrder[TypeOrder["GEO_POINT"] = 7] = "GEO_POINT";
TypeOrder[TypeOrder["ARRAY"] = 8] = "ARRAY";
TypeOrder[TypeOrder["OBJECT"] = 9] = "OBJECT";
})(TypeOrder || (TypeOrder = {}));
/*!
* @private
*/
function typeOrder(val) {
const valueType = convert_1.detectValueType(val);
switch (valueType) {
case 'nullValue':
return TypeOrder.NULL;
case 'integerValue':
return TypeOrder.NUMBER;
case 'doubleValue':
return TypeOrder.NUMBER;
case 'stringValue':
return TypeOrder.STRING;
case 'booleanValue':
return TypeOrder.BOOLEAN;
case 'arrayValue':
return TypeOrder.ARRAY;
case 'timestampValue':
return TypeOrder.TIMESTAMP;
case 'geoPointValue':
return TypeOrder.GEO_POINT;
case 'bytesValue':
return TypeOrder.BLOB;
case 'referenceValue':
return TypeOrder.REF;
case 'mapValue':
return TypeOrder.OBJECT;
default:
throw new Error('Unexpected value type: ' + valueType);
}
}
/*!
* @private
*/
function primitiveComparator(left, right) {
if (left < right) {
return -1;
}
if (left > right) {
return 1;
}
return 0;
}
exports.primitiveComparator = primitiveComparator;
/*!
* Utility function to compare doubles (using Firestore semantics for NaN).
* @private
*/
function compareNumbers(left, right) {
if (left < right) {
return -1;
}
if (left > right) {
return 1;
}
if (left === right) {
return 0;
}
// one or both are NaN.
if (isNaN(left)) {
return isNaN(right) ? 0 : -1;
}
return 1;
}
/*!
* @private
*/
function compareNumberProtos(left, right) {
let leftValue, rightValue;
if (left.integerValue !== undefined) {
leftValue = Number(left.integerValue);
}
else {
leftValue = Number(left.doubleValue);
}
if (right.integerValue !== undefined) {
rightValue = Number(right.integerValue);
}
else {
rightValue = Number(right.doubleValue);
}
return compareNumbers(leftValue, rightValue);
}
/*!
* @private
*/
function compareTimestamps(left, right) {
const seconds = primitiveComparator(left.seconds || 0, right.seconds || 0);
if (seconds !== 0) {
return seconds;
}
return primitiveComparator(left.nanos || 0, right.nanos || 0);
}
/*!
* @private
*/
function compareBlobs(left, right) {
if (!(left instanceof Buffer) || !(right instanceof Buffer)) {
throw new Error('Blobs can only be compared if they are Buffers.');
}
return Buffer.compare(left, right);
}
/*!
* @private
*/
function compareReferenceProtos(left, right) {
const leftPath = path_1.QualifiedResourcePath.fromSlashSeparatedString(left.referenceValue);
const rightPath = path_1.QualifiedResourcePath.fromSlashSeparatedString(right.referenceValue);
return leftPath.compareTo(rightPath);
}
/*!
* @private
*/
function compareGeoPoints(left, right) {
return (primitiveComparator(left.latitude || 0, right.latitude || 0) ||
primitiveComparator(left.longitude || 0, right.longitude || 0));
}
/*!
* @private
*/
function compareArrays(left, right) {
for (let i = 0; i < left.length && i < right.length; i++) {
const valueComparison = compare(left[i], right[i]);
if (valueComparison !== 0) {
return valueComparison;
}
}
// If all the values matched so far, just check the length.
return primitiveComparator(left.length, right.length);
}
/*!
* @private
*/
function compareObjects(left, right) {
// This requires iterating over the keys in the object in order and doing a
// deep comparison.
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
leftKeys.sort();
rightKeys.sort();
for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
const keyComparison = primitiveComparator(leftKeys[i], rightKeys[i]);
if (keyComparison !== 0) {
return keyComparison;
}
const key = leftKeys[i];
const valueComparison = compare(left[key], right[key]);
if (valueComparison !== 0) {
return valueComparison;
}
}
// If all the keys matched so far, just check the length.
return primitiveComparator(leftKeys.length, rightKeys.length);
}
/*!
* @private
*/
function compare(left, right) {
// First compare the types.
const leftType = typeOrder(left);
const rightType = typeOrder(right);
const typeComparison = primitiveComparator(leftType, rightType);
if (typeComparison !== 0) {
return typeComparison;
}
// So they are the same type.
switch (leftType) {
case TypeOrder.NULL:
// Nulls are all equal.
return 0;
case TypeOrder.BOOLEAN:
return primitiveComparator(left.booleanValue, right.booleanValue);
case TypeOrder.STRING:
return primitiveComparator(left.stringValue, right.stringValue);
case TypeOrder.NUMBER:
return compareNumberProtos(left, right);
case TypeOrder.TIMESTAMP:
return compareTimestamps(left.timestampValue, right.timestampValue);
case TypeOrder.BLOB:
return compareBlobs(left.bytesValue, right.bytesValue);
case TypeOrder.REF:
return compareReferenceProtos(left, right);
case TypeOrder.GEO_POINT:
return compareGeoPoints(left.geoPointValue, right.geoPointValue);
case TypeOrder.ARRAY:
return compareArrays(left.arrayValue.values || [], right.arrayValue.values || []);
case TypeOrder.OBJECT:
return compareObjects(left.mapValue.fields || {}, right.mapValue.fields || {});
default:
throw new Error(`Encountered unknown type order: ${leftType}`);
}
}
exports.compare = compare;
//# sourceMappingURL=order.js.map

View File

@ -0,0 +1,363 @@
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { google } from '../protos/firestore_v1_proto_api';
import api = google.firestore.v1;
/*!
* The default database ID for this Firestore client. We do not yet expose the
* ability to use different databases.
*/
export declare const DEFAULT_DATABASE_ID = "(default)";
/**
* An abstract class representing a Firestore path.
*
* Subclasses have to implement `split()` and `canonicalString()`.
*
* @private
* @class
*/
declare abstract class Path<T> {
protected readonly segments: string[];
/**
* Creates a new Path with the given segments.
*
* @private
* @hideconstructor
* @param segments Sequence of parts of a path.
*/
constructor(segments: string[]);
/**
* Returns the number of segments of this field path.
*
* @private
*/
readonly size: number;
abstract construct(segments: string[] | string): T;
abstract split(relativePath: string): string[];
/**
* Create a child path beneath the current level.
*
* @private
* @param relativePath Relative path to append to the current path.
* @returns The new path.
*/
append(relativePath: Path<T> | string): T;
/**
* Returns the path of the parent node.
*
* @private
* @returns The new path or null if we are already at the root.
*/
parent(): T | null;
/**
* Checks whether the current path is a prefix of the specified path.
*
* @private
* @param other The path to check against.
* @returns 'true' iff the current path is a prefix match with 'other'.
*/
isPrefixOf(other: Path<T>): boolean;
/**
* Compare the current path against another Path object.
*
* @private
* @param other The path to compare to.
* @returns -1 if current < other, 1 if current > other, 0 if equal
*/
compareTo(other: Path<T>): number;
/**
* Returns a copy of the underlying segments.
*
* @private
* @returns A copy of the segments that make up this path.
*/
toArray(): string[];
/**
* Returns true if this `Path` is equal to the provided value.
*
* @private
* @param other The value to compare against.
* @return true if this `Path` is equal to the provided value.
*/
isEqual(other: Path<T>): boolean;
}
/**
* A slash-separated path for navigating resources within the current Firestore
* instance.
*
* @private
*/
export declare class ResourcePath extends Path<ResourcePath> {
/**
* A default instance pointing to the root collection.
* @private
*/
static EMPTY: ResourcePath;
/**
* Constructs a ResourcePath.
*
* @private
* @param segments Sequence of names of the parts of the path.
*/
constructor(...segments: string[]);
/**
* Indicates whether this path points to a document.
* @private
*/
readonly isDocument: boolean;
/**
* Indicates whether this path points to a collection.
* @private
*/
readonly isCollection: boolean;
/**
* The last component of the path.
* @private
*/
readonly id: string | null;
/**
* Returns the location of this path relative to the root of the project's
* database.
* @private
*/
readonly relativeName: string;
/**
* Constructs a new instance of ResourcePath.
*
* @private
* @param segments Sequence of parts of the path.
* @returns The newly created ResourcePath.
*/
construct(segments: string[]): ResourcePath;
/**
* Splits a string into path segments, using slashes as separators.
*
* @private
* @param relativePath The path to split.
* @returns The split path segments.
*/
split(relativePath: string): string[];
/**
* Converts this path to a fully qualified ResourcePath.
*
* @private
* @param projectIdIfMissing The project ID of the current Firestore project.
* The project ID is only used if it's not provided as part of this
* ResourcePath.
* @return A fully-qualified resource path pointing to the same element.
*/
toQualifiedResourcePath(projectIdIfMissing: string): QualifiedResourcePath;
}
/**
* A slash-separated path that includes a project and database ID for referring
* to resources in any Firestore project.
*
* @private
*/
export declare class QualifiedResourcePath extends ResourcePath {
/**
* The project ID of this path.
*/
readonly projectId: string;
/**
* The database ID of this path.
*/
readonly databaseId: string;
/**
* Constructs a Firestore Resource Path.
*
* @private
* @param projectId The Firestore project id.
* @param databaseId The Firestore database id.
* @param segments Sequence of names of the parts of the path.
*/
constructor(projectId: string, databaseId: string, ...segments: string[]);
/**
* String representation of the path relative to the database root.
* @private
*/
readonly relativeName: string;
/**
* Creates a resource path from an absolute Firestore path.
*
* @private
* @param absolutePath A string representation of a Resource Path.
* @returns The new ResourcePath.
*/
static fromSlashSeparatedString(absolutePath: string): QualifiedResourcePath;
/**
* Create a child path beneath the current level.
*
* @private
* @param relativePath Relative path to append to the current path.
* @returns The new path.
*/
append(relativePath: ResourcePath | string): QualifiedResourcePath;
/**
* Create a child path beneath the current level.
*
* @private
* @returns The new path.
*/
parent(): QualifiedResourcePath | null;
/**
* String representation of a ResourcePath as expected by the API.
*
* @private
* @returns The representation as expected by the API.
*/
readonly formattedName: string;
/**
* Constructs a new instance of ResourcePath. We need this instead of using
* the normal constructor because polymorphic 'this' doesn't work on static
* methods.
*
* @private
* @param segments Sequence of names of the parts of the path.
* @returns The newly created QualifiedResourcePath.
*/
construct(segments: string[]): QualifiedResourcePath;
/**
* Convenience method to match the ResourcePath API. This method always
* returns the current instance. The arguments is ignored.
*
* @param projectIdIfMissing The project ID of the current Firestore project.
* The project ID is only used if it's not provided as part of this
* ResourcePath.
* @private
*/
toQualifiedResourcePath(projectIdIfMissing: string): QualifiedResourcePath;
/**
* Compare the current path against another ResourcePath object.
*
* @private
* @param other The path to compare to.
* @returns -1 if current < other, 1 if current > other, 0 if equal
*/
compareTo(other: ResourcePath): number;
/**
* Converts this ResourcePath to the Firestore Proto representation.
* @private
*/
toProto(): api.IValue;
}
/**
* Validates that the given string can be used as a relative or absolute
* resource path.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param resourcePath The path to validate.
* @throws if the string can't be used as a resource path.
*/
export declare function validateResourcePath(arg: string | number, resourcePath: string): void;
/**
* A dot-separated path for navigating sub-objects within a document.
*
* @class
*/
export declare class FieldPath extends Path<FieldPath> {
/**
* A special sentinel value to refer to the ID of a document.
*
* @private
*/
private static _DOCUMENT_ID;
/**
* Constructs a Firestore Field Path.
*
* @param {...string} segments Sequence of field names that form this path.
*
* @example
* let query = firestore.collection('col');
* let fieldPath = new FieldPath('f.o.o', 'bar');
*
* query.where(fieldPath, '==', 42).get().then(snapshot => {
* snapshot.forEach(document => {
* console.log(`Document contains {'f.o.o' : {'bar' : 42}}`);
* });
* });
*/
constructor(...segments: string[]);
/**
* A special FieldPath value to refer to the ID of a document. It can be used
* in queries to sort or filter by the document ID.
*
* @returns {FieldPath}
*/
static documentId(): FieldPath;
/**
* Turns a field path argument into a [FieldPath]{@link FieldPath}.
* Supports FieldPaths as input (which are passed through) and dot-separated
* strings.
*
* @private
* @param {string|FieldPath} fieldPath The FieldPath to create.
* @returns {FieldPath} A field path representation.
*/
static fromArgument(fieldPath: string | FieldPath): FieldPath;
/**
* String representation of a FieldPath as expected by the API.
*
* @private
* @override
* @returns {string} The representation as expected by the API.
*/
readonly formattedName: string;
/**
* Returns a string representation of this path.
*
* @private
* @returns A string representing this path.
*/
toString(): string;
/**
* Splits a string into path segments, using dots as separators.
*
* @private
* @override
* @param {string} fieldPath The path to split.
* @returns {Array.<string>} - The split path segments.
*/
split(fieldPath: string): string[];
/**
* Constructs a new instance of FieldPath. We need this instead of using
* the normal constructor because polymorphic 'this' doesn't work on static
* methods.
*
* @private
* @override
* @param segments Sequence of field names.
* @returns The newly created FieldPath.
*/
construct(segments: string[]): FieldPath;
/**
* Returns true if this `FieldPath` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `FieldPath` is equal to the provided value.
*/
isEqual(other: FieldPath): boolean;
}
/**
* Validates that the provided value can be used as a field path argument.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param fieldPath The value to verify.
* @throws if the string can't be used as a field path.
*/
export declare function validateFieldPath(arg: string | number, fieldPath: unknown): void;
export {};

573
node_modules/@google-cloud/firestore/build/src/path.js generated vendored Normal file
View File

@ -0,0 +1,573 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("./util");
const validate_1 = require("./validate");
/*!
* The default database ID for this Firestore client. We do not yet expose the
* ability to use different databases.
*/
exports.DEFAULT_DATABASE_ID = '(default)';
/*!
* A regular expression to verify an absolute Resource Path in Firestore. It
* extracts the project ID, the database name and the relative resource path
* if available.
*
* @type {RegExp}
*/
const RESOURCE_PATH_RE =
// Note: [\s\S] matches all characters including newlines.
/^projects\/([^/]*)\/databases\/([^/]*)(?:\/documents\/)?([\s\S]*)$/;
/*!
* A regular expression to verify whether a field name can be passed to the
* backend without escaping.
*
* @type {RegExp}
*/
const UNESCAPED_FIELD_NAME_RE = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
/*!
* A regular expression to verify field paths that are passed to the API as
* strings. Field paths that do not match this expression have to be provided
* as a [FieldPath]{@link FieldPath} object.
*
* @type {RegExp}
*/
const FIELD_PATH_RE = /^[^*~/[\]]+$/;
/**
* An abstract class representing a Firestore path.
*
* Subclasses have to implement `split()` and `canonicalString()`.
*
* @private
* @class
*/
class Path {
/**
* Creates a new Path with the given segments.
*
* @private
* @hideconstructor
* @param segments Sequence of parts of a path.
*/
constructor(segments) {
this.segments = segments;
}
/**
* Returns the number of segments of this field path.
*
* @private
*/
get size() {
return this.segments.length;
}
/**
* Create a child path beneath the current level.
*
* @private
* @param relativePath Relative path to append to the current path.
* @returns The new path.
*/
append(relativePath) {
if (relativePath instanceof Path) {
return this.construct(this.segments.concat(relativePath.segments));
}
return this.construct(this.segments.concat(this.split(relativePath)));
}
/**
* Returns the path of the parent node.
*
* @private
* @returns The new path or null if we are already at the root.
*/
parent() {
if (this.segments.length === 0) {
return null;
}
return this.construct(this.segments.slice(0, this.segments.length - 1));
}
/**
* Checks whether the current path is a prefix of the specified path.
*
* @private
* @param other The path to check against.
* @returns 'true' iff the current path is a prefix match with 'other'.
*/
isPrefixOf(other) {
if (other.segments.length < this.segments.length) {
return false;
}
for (let i = 0; i < this.segments.length; i++) {
if (this.segments[i] !== other.segments[i]) {
return false;
}
}
return true;
}
/**
* Compare the current path against another Path object.
*
* @private
* @param other The path to compare to.
* @returns -1 if current < other, 1 if current > other, 0 if equal
*/
compareTo(other) {
const len = Math.min(this.segments.length, other.segments.length);
for (let i = 0; i < len; i++) {
if (this.segments[i] < other.segments[i]) {
return -1;
}
if (this.segments[i] > other.segments[i]) {
return 1;
}
}
if (this.segments.length < other.segments.length) {
return -1;
}
if (this.segments.length > other.segments.length) {
return 1;
}
return 0;
}
/**
* Returns a copy of the underlying segments.
*
* @private
* @returns A copy of the segments that make up this path.
*/
toArray() {
return this.segments.slice();
}
/**
* Returns true if this `Path` is equal to the provided value.
*
* @private
* @param other The value to compare against.
* @return true if this `Path` is equal to the provided value.
*/
isEqual(other) {
return (this === other ||
(other instanceof this.constructor && this.compareTo(other) === 0));
}
}
/**
* A slash-separated path for navigating resources within the current Firestore
* instance.
*
* @private
*/
class ResourcePath extends Path {
/**
* Constructs a ResourcePath.
*
* @private
* @param segments Sequence of names of the parts of the path.
*/
constructor(...segments) {
super(segments);
}
/**
* Indicates whether this path points to a document.
* @private
*/
get isDocument() {
return this.segments.length > 0 && this.segments.length % 2 === 0;
}
/**
* Indicates whether this path points to a collection.
* @private
*/
get isCollection() {
return this.segments.length % 2 === 1;
}
/**
* The last component of the path.
* @private
*/
get id() {
if (this.segments.length > 0) {
return this.segments[this.segments.length - 1];
}
return null;
}
/**
* Returns the location of this path relative to the root of the project's
* database.
* @private
*/
get relativeName() {
return this.segments.join('/');
}
/**
* Constructs a new instance of ResourcePath.
*
* @private
* @param segments Sequence of parts of the path.
* @returns The newly created ResourcePath.
*/
construct(segments) {
return new ResourcePath(...segments);
}
/**
* Splits a string into path segments, using slashes as separators.
*
* @private
* @param relativePath The path to split.
* @returns The split path segments.
*/
split(relativePath) {
// We may have an empty segment at the beginning or end if they had a
// leading or trailing slash (which we allow).
return relativePath.split('/').filter(segment => segment.length > 0);
}
/**
* Converts this path to a fully qualified ResourcePath.
*
* @private
* @param projectIdIfMissing The project ID of the current Firestore project.
* The project ID is only used if it's not provided as part of this
* ResourcePath.
* @return A fully-qualified resource path pointing to the same element.
*/
toQualifiedResourcePath(projectIdIfMissing) {
return new QualifiedResourcePath(projectIdIfMissing, exports.DEFAULT_DATABASE_ID, ...this.segments);
}
}
exports.ResourcePath = ResourcePath;
/**
* A default instance pointing to the root collection.
* @private
*/
ResourcePath.EMPTY = new ResourcePath();
/**
* A slash-separated path that includes a project and database ID for referring
* to resources in any Firestore project.
*
* @private
*/
class QualifiedResourcePath extends ResourcePath {
/**
* Constructs a Firestore Resource Path.
*
* @private
* @param projectId The Firestore project id.
* @param databaseId The Firestore database id.
* @param segments Sequence of names of the parts of the path.
*/
constructor(projectId, databaseId, ...segments) {
super(...segments);
this.projectId = projectId;
this.databaseId = databaseId;
}
/**
* String representation of the path relative to the database root.
* @private
*/
get relativeName() {
return this.segments.join('/');
}
/**
* Creates a resource path from an absolute Firestore path.
*
* @private
* @param absolutePath A string representation of a Resource Path.
* @returns The new ResourcePath.
*/
static fromSlashSeparatedString(absolutePath) {
const elements = RESOURCE_PATH_RE.exec(absolutePath);
if (elements) {
const project = elements[1];
const database = elements[2];
const path = elements[3];
return new QualifiedResourcePath(project, database).append(path);
}
throw new Error(`Resource name '${absolutePath}' is not valid.`);
}
/**
* Create a child path beneath the current level.
*
* @private
* @param relativePath Relative path to append to the current path.
* @returns The new path.
*/
append(relativePath) {
// `super.append()` calls `QualifiedResourcePath.construct()` when invoked
// from here and returns a QualifiedResourcePath.
return super.append(relativePath);
}
/**
* Create a child path beneath the current level.
*
* @private
* @returns The new path.
*/
parent() {
return super.parent();
}
/**
* String representation of a ResourcePath as expected by the API.
*
* @private
* @returns The representation as expected by the API.
*/
get formattedName() {
const components = [
'projects',
this.projectId,
'databases',
this.databaseId,
'documents',
...this.segments,
];
return components.join('/');
}
/**
* Constructs a new instance of ResourcePath. We need this instead of using
* the normal constructor because polymorphic 'this' doesn't work on static
* methods.
*
* @private
* @param segments Sequence of names of the parts of the path.
* @returns The newly created QualifiedResourcePath.
*/
construct(segments) {
return new QualifiedResourcePath(this.projectId, this.databaseId, ...segments);
}
/**
* Convenience method to match the ResourcePath API. This method always
* returns the current instance. The arguments is ignored.
*
* @param projectIdIfMissing The project ID of the current Firestore project.
* The project ID is only used if it's not provided as part of this
* ResourcePath.
* @private
*/
toQualifiedResourcePath(projectIdIfMissing) {
return this;
}
/**
* Compare the current path against another ResourcePath object.
*
* @private
* @param other The path to compare to.
* @returns -1 if current < other, 1 if current > other, 0 if equal
*/
compareTo(other) {
if (other instanceof QualifiedResourcePath) {
if (this.projectId < other.projectId) {
return -1;
}
if (this.projectId > other.projectId) {
return 1;
}
if (this.databaseId < other.databaseId) {
return -1;
}
if (this.databaseId > other.databaseId) {
return 1;
}
}
return super.compareTo(other);
}
/**
* Converts this ResourcePath to the Firestore Proto representation.
* @private
*/
toProto() {
return {
referenceValue: this.formattedName,
};
}
}
exports.QualifiedResourcePath = QualifiedResourcePath;
/**
* Validates that the given string can be used as a relative or absolute
* resource path.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param resourcePath The path to validate.
* @throws if the string can't be used as a resource path.
*/
function validateResourcePath(arg, resourcePath) {
if (typeof resourcePath !== 'string' || resourcePath === '') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'resource path')} Path must be a non-empty string.`);
}
if (resourcePath.indexOf('//') >= 0) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'resource path')} Paths must not contain //.`);
}
}
exports.validateResourcePath = validateResourcePath;
/**
* A dot-separated path for navigating sub-objects within a document.
*
* @class
*/
class FieldPath extends Path {
/**
* Constructs a Firestore Field Path.
*
* @param {...string} segments Sequence of field names that form this path.
*
* @example
* let query = firestore.collection('col');
* let fieldPath = new FieldPath('f.o.o', 'bar');
*
* query.where(fieldPath, '==', 42).get().then(snapshot => {
* snapshot.forEach(document => {
* console.log(`Document contains {'f.o.o' : {'bar' : 42}}`);
* });
* });
*/
constructor(...segments) {
if (Array.isArray(segments[0])) {
throw new Error('The FieldPath constructor no longer supports an array as its first argument. ' +
'Please unpack your array and call FieldPath() with individual arguments.');
}
validate_1.validateMinNumberOfArguments('FieldPath', segments, 1);
for (let i = 0; i < segments.length; ++i) {
validate_1.validateString(i, segments[i]);
if (segments[i].length === 0) {
throw new Error(`Element at index ${i} should not be an empty string.`);
}
}
super(segments);
}
/**
* A special FieldPath value to refer to the ID of a document. It can be used
* in queries to sort or filter by the document ID.
*
* @returns {FieldPath}
*/
static documentId() {
return FieldPath._DOCUMENT_ID;
}
/**
* Turns a field path argument into a [FieldPath]{@link FieldPath}.
* Supports FieldPaths as input (which are passed through) and dot-separated
* strings.
*
* @private
* @param {string|FieldPath} fieldPath The FieldPath to create.
* @returns {FieldPath} A field path representation.
*/
static fromArgument(fieldPath) {
// validateFieldPath() is used in all public API entry points to validate
// that fromArgument() is only called with a Field Path or a string.
return fieldPath instanceof FieldPath
? fieldPath
: new FieldPath(...fieldPath.split('.'));
}
/**
* String representation of a FieldPath as expected by the API.
*
* @private
* @override
* @returns {string} The representation as expected by the API.
*/
get formattedName() {
return this.segments
.map(str => {
return UNESCAPED_FIELD_NAME_RE.test(str)
? str
: '`' + str.replace('\\', '\\\\').replace('`', '\\`') + '`';
})
.join('.');
}
/**
* Returns a string representation of this path.
*
* @private
* @returns A string representing this path.
*/
toString() {
return this.formattedName;
}
/**
* Splits a string into path segments, using dots as separators.
*
* @private
* @override
* @param {string} fieldPath The path to split.
* @returns {Array.<string>} - The split path segments.
*/
split(fieldPath) {
return fieldPath.split('.');
}
/**
* Constructs a new instance of FieldPath. We need this instead of using
* the normal constructor because polymorphic 'this' doesn't work on static
* methods.
*
* @private
* @override
* @param segments Sequence of field names.
* @returns The newly created FieldPath.
*/
construct(segments) {
return new FieldPath(...segments);
}
/**
* Returns true if this `FieldPath` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `FieldPath` is equal to the provided value.
*/
isEqual(other) {
return super.isEqual(other);
}
}
exports.FieldPath = FieldPath;
/**
* A special sentinel value to refer to the ID of a document.
*
* @private
*/
FieldPath._DOCUMENT_ID = new FieldPath('__name__');
/**
* Validates that the provided value can be used as a field path argument.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param fieldPath The value to verify.
* @throws if the string can't be used as a field path.
*/
function validateFieldPath(arg, fieldPath) {
if (fieldPath instanceof FieldPath) {
return;
}
if (fieldPath === undefined) {
throw new Error(validate_1.invalidArgumentMessage(arg, 'field path') + ' The path cannot be omitted.');
}
if (util_1.isObject(fieldPath) && fieldPath.constructor.name === 'FieldPath') {
throw new Error(validate_1.customObjectMessage(arg, fieldPath));
}
if (typeof fieldPath !== 'string') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'field path')} Paths can only be specified as strings or via a FieldPath object.`);
}
if (fieldPath.indexOf('..') >= 0) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'field path')} Paths must not contain ".." in them.`);
}
if (fieldPath.startsWith('.') || fieldPath.endsWith('.')) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'field path')} Paths must not start or end with ".".`);
}
if (!FIELD_PATH_RE.test(fieldPath)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'field path')} Paths can't be empty and must not contain
"*~/[]".`);
}
}
exports.validateFieldPath = validateFieldPath;
//# sourceMappingURL=path.js.map

View File

@ -0,0 +1,98 @@
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* An auto-resizing pool that distributes concurrent operations over multiple
* clients of type `T`.
*
* ClientPool is used within Firestore to manage a pool of GAPIC clients and
* automatically initializes multiple clients if we issue more than 100
* concurrent operations.
*
* @private
*/
export declare class ClientPool<T> {
private readonly concurrentOperationLimit;
private readonly maxIdleClients;
private readonly clientFactory;
private readonly clientDestructor;
/**
* Stores each active clients and how many operations it has outstanding.
* @private
*/
private activeClients;
/**
* Whether the Firestore instance has been terminated. Once terminated, the
* ClientPool can longer schedule new operations.
*/
private terminated;
/**
* @param concurrentOperationLimit The number of operations that each client
* can handle.
* @param maxIdleClients The maximum number of idle clients to keep before
* garbage collecting.
* @param clientFactory A factory function called as needed when new clients
* are required.
* @param clientDestructor A cleanup function that is called when a client is
* disposed of.
*/
constructor(concurrentOperationLimit: number, maxIdleClients: number, clientFactory: () => T, clientDestructor?: (client: T) => Promise<void>);
/**
* Returns an already existing client if it has less than the maximum number
* of concurrent operations or initializes and returns a new client.
*
* @private
*/
private acquire;
/**
* Reduces the number of operations for the provided client, potentially
* removing it from the pool of active clients.
* @private
*/
private release;
/**
* Given the current operation counts, determines if the given client should
* be garbage collected.
* @private
*/
private shouldGarbageCollectClient;
/**
* The number of currently registered clients.
*
* @return Number of currently registered clients.
* @private
*/
readonly size: number;
/**
* The number of currently active operations.
*
* @return Number of currently active operations.
* @private
*/
readonly opCount: number;
/**
* Runs the provided operation in this pool. This function may create an
* additional client if all existing clients already operate at the concurrent
* operation limit.
*
* @param requestTag A unique client-assigned identifier for this operation.
* @param op A callback function that returns a Promise. The client T will
* be returned to the pool when callback finishes.
* @return A Promise that resolves with the result of `op`.
* @private
*/
run<V>(requestTag: string, op: (client: T) => Promise<V>): Promise<V>;
terminate(): Promise<void>;
}

175
node_modules/@google-cloud/firestore/build/src/pool.js generated vendored Normal file
View File

@ -0,0 +1,175 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const assert = require("assert");
const logger_1 = require("./logger");
/**
* An auto-resizing pool that distributes concurrent operations over multiple
* clients of type `T`.
*
* ClientPool is used within Firestore to manage a pool of GAPIC clients and
* automatically initializes multiple clients if we issue more than 100
* concurrent operations.
*
* @private
*/
class ClientPool {
/**
* @param concurrentOperationLimit The number of operations that each client
* can handle.
* @param maxIdleClients The maximum number of idle clients to keep before
* garbage collecting.
* @param clientFactory A factory function called as needed when new clients
* are required.
* @param clientDestructor A cleanup function that is called when a client is
* disposed of.
*/
constructor(concurrentOperationLimit, maxIdleClients, clientFactory, clientDestructor = () => Promise.resolve()) {
this.concurrentOperationLimit = concurrentOperationLimit;
this.maxIdleClients = maxIdleClients;
this.clientFactory = clientFactory;
this.clientDestructor = clientDestructor;
/**
* Stores each active clients and how many operations it has outstanding.
* @private
*/
this.activeClients = new Map();
/**
* Whether the Firestore instance has been terminated. Once terminated, the
* ClientPool can longer schedule new operations.
*/
this.terminated = false;
}
/**
* Returns an already existing client if it has less than the maximum number
* of concurrent operations or initializes and returns a new client.
*
* @private
*/
acquire(requestTag) {
let selectedClient = null;
let selectedClientRequestCount = -1;
for (const [client, requestCount] of this.activeClients) {
// Use the "most-full" client that can still accommodate the request
// in order to maximize the number of idle clients as operations start to
// complete.
if (requestCount > selectedClientRequestCount &&
requestCount < this.concurrentOperationLimit) {
selectedClient = client;
selectedClientRequestCount = requestCount;
}
}
if (selectedClient) {
logger_1.logger('ClientPool.acquire', requestTag, 'Re-using existing client with %s remaining operations', this.concurrentOperationLimit - selectedClientRequestCount);
}
else {
logger_1.logger('ClientPool.acquire', requestTag, 'Creating a new client');
selectedClient = this.clientFactory();
selectedClientRequestCount = 0;
assert(!this.activeClients.has(selectedClient), 'The provided client factory returned an existing instance');
}
this.activeClients.set(selectedClient, selectedClientRequestCount + 1);
return selectedClient;
}
/**
* Reduces the number of operations for the provided client, potentially
* removing it from the pool of active clients.
* @private
*/
async release(requestTag, client) {
const requestCount = this.activeClients.get(client) || 0;
assert(requestCount > 0, 'No active request');
this.activeClients.set(client, requestCount - 1);
if (this.shouldGarbageCollectClient(client)) {
this.activeClients.delete(client);
await this.clientDestructor(client);
logger_1.logger('ClientPool.release', requestTag, 'Garbage collected 1 client');
}
}
/**
* Given the current operation counts, determines if the given client should
* be garbage collected.
* @private
*/
shouldGarbageCollectClient(client) {
if (this.activeClients.get(client) !== 0) {
return false;
}
let idleCapacityCount = 0;
for (const [_, count] of this.activeClients) {
idleCapacityCount += this.concurrentOperationLimit - count;
}
return (idleCapacityCount > this.maxIdleClients * this.concurrentOperationLimit);
}
/**
* The number of currently registered clients.
*
* @return Number of currently registered clients.
* @private
*/
// Visible for testing.
get size() {
return this.activeClients.size;
}
/**
* The number of currently active operations.
*
* @return Number of currently active operations.
* @private
*/
// Visible for testing.
get opCount() {
let activeOperationCount = 0;
this.activeClients.forEach(count => (activeOperationCount += count));
return activeOperationCount;
}
/**
* Runs the provided operation in this pool. This function may create an
* additional client if all existing clients already operate at the concurrent
* operation limit.
*
* @param requestTag A unique client-assigned identifier for this operation.
* @param op A callback function that returns a Promise. The client T will
* be returned to the pool when callback finishes.
* @return A Promise that resolves with the result of `op`.
* @private
*/
run(requestTag, op) {
if (this.terminated) {
return Promise.reject('The client has already been terminated');
}
const client = this.acquire(requestTag);
return op(client)
.catch(async (err) => {
await this.release(requestTag, client);
return Promise.reject(err);
})
.then(async (res) => {
await this.release(requestTag, client);
return res;
});
}
async terminate() {
this.terminated = true;
for (const [client, _requestCount] of this.activeClients) {
this.activeClients.delete(client);
await this.clientDestructor(client);
}
}
}
exports.ClientPool = ClientPool;
//# sourceMappingURL=pool.js.map

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,77 @@
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as proto from '../protos/firestore_v1_proto_api';
import { Firestore } from './index';
import { FieldPath } from './path';
import { ApiMapValue, DocumentData, ValidationOptions } from './types';
import api = proto.google.firestore.v1;
/**
* An interface for Firestore types that can be serialized to Protobuf.
*
* @private
*/
export interface Serializable {
toProto(): api.IValue;
}
/**
* Serializer that is used to convert between JavaScript types and their
* Firestore Protobuf representation.
*
* @private
*/
export declare class Serializer {
private createReference;
constructor(firestore: Firestore);
/**
* Encodes a JavaScript object into the Firestore 'Fields' representation.
*
* @private
* @param obj The object to encode.
* @returns The Firestore 'Fields' representation
*/
encodeFields(obj: DocumentData): ApiMapValue;
/**
* Encodes a JavaScript value into the Firestore 'Value' representation.
*
* @private
* @param val The object to encode
* @returns The Firestore Proto or null if we are deleting a field.
*/
encodeValue(val: unknown): api.IValue | null;
/**
* Decodes a single Firestore 'Value' Protobuf.
*
* @private
* @param proto A Firestore 'Value' Protobuf.
* @returns The converted JS type.
*/
decodeValue(proto: api.IValue): unknown;
}
/**
* Validates a JavaScript value for usage as a Firestore value.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value JavaScript value to validate.
* @param desc A description of the expected type.
* @param path The field path to validate.
* @param options Validation options
* @param level The current depth of the traversal. This is used to decide
* whether deletes are allowed in conjunction with `allowDeletes: root`.
* @param inArray Whether we are inside an array.
* @throws when the object is invalid.
*/
export declare function validateUserInput(arg: string | number, value: unknown, desc: string, options: ValidationOptions, path?: FieldPath, level?: number, inArray?: boolean): void;

View File

@ -0,0 +1,316 @@
"use strict";
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const convert_1 = require("./convert");
const field_value_1 = require("./field-value");
const field_value_2 = require("./field-value");
const geo_point_1 = require("./geo-point");
const index_1 = require("./index");
const path_1 = require("./path");
const timestamp_1 = require("./timestamp");
const util_1 = require("./util");
const validate_1 = require("./validate");
/**
* The maximum depth of a Firestore object.
*
* @private
*/
const MAX_DEPTH = 20;
/**
* Serializer that is used to convert between JavaScript types and their
* Firestore Protobuf representation.
*
* @private
*/
class Serializer {
constructor(firestore) {
// Instead of storing the `firestore` object, we store just a reference to
// its `.doc()` method. This avoid a circular reference, which breaks
// JSON.stringify().
this.createReference = path => firestore.doc(path);
}
/**
* Encodes a JavaScript object into the Firestore 'Fields' representation.
*
* @private
* @param obj The object to encode.
* @returns The Firestore 'Fields' representation
*/
encodeFields(obj) {
const fields = {};
for (const prop of Object.keys(obj)) {
const val = this.encodeValue(obj[prop]);
if (val) {
fields[prop] = val;
}
}
return fields;
}
/**
* Encodes a JavaScript value into the Firestore 'Value' representation.
*
* @private
* @param val The object to encode
* @returns The Firestore Proto or null if we are deleting a field.
*/
encodeValue(val) {
if (val instanceof field_value_1.FieldTransform) {
return null;
}
if (typeof val === 'string') {
return {
stringValue: val,
};
}
if (typeof val === 'boolean') {
return {
booleanValue: val,
};
}
if (typeof val === 'number') {
if (Number.isSafeInteger(val)) {
return {
integerValue: val,
};
}
else {
return {
doubleValue: val,
};
}
}
if (val instanceof Date) {
const timestamp = timestamp_1.Timestamp.fromDate(val);
return {
timestampValue: {
seconds: timestamp.seconds,
nanos: timestamp.nanoseconds,
},
};
}
if (isMomentJsType(val)) {
const timestamp = timestamp_1.Timestamp.fromDate(val.toDate());
return {
timestampValue: {
seconds: timestamp.seconds,
nanos: timestamp.nanoseconds,
},
};
}
if (val === null) {
return {
nullValue: 'NULL_VALUE',
};
}
if (val instanceof Buffer || val instanceof Uint8Array) {
return {
bytesValue: val,
};
}
if (util_1.isObject(val)) {
const toProto = val['toProto'];
if (typeof toProto === 'function') {
return toProto.bind(val)();
}
}
if (val instanceof Array) {
const array = {
arrayValue: {},
};
if (val.length > 0) {
array.arrayValue.values = [];
for (let i = 0; i < val.length; ++i) {
const enc = this.encodeValue(val[i]);
if (enc) {
array.arrayValue.values.push(enc);
}
}
}
return array;
}
if (typeof val === 'object' && util_1.isPlainObject(val)) {
const map = {
mapValue: {},
};
// If we encounter an empty object, we always need to send it to make sure
// the server creates a map entry.
if (!util_1.isEmpty(val)) {
map.mapValue.fields = this.encodeFields(val);
if (util_1.isEmpty(map.mapValue.fields)) {
return null;
}
}
return map;
}
throw new Error(`Cannot encode value: ${val}`);
}
/**
* Decodes a single Firestore 'Value' Protobuf.
*
* @private
* @param proto A Firestore 'Value' Protobuf.
* @returns The converted JS type.
*/
decodeValue(proto) {
const valueType = convert_1.detectValueType(proto);
switch (valueType) {
case 'stringValue': {
return proto.stringValue;
}
case 'booleanValue': {
return proto.booleanValue;
}
case 'integerValue': {
return Number(proto.integerValue);
}
case 'doubleValue': {
return Number(proto.doubleValue);
}
case 'timestampValue': {
const timestamp = timestamp_1.Timestamp.fromProto(proto.timestampValue);
return timestamp;
}
case 'referenceValue': {
const resourcePath = path_1.QualifiedResourcePath.fromSlashSeparatedString(proto.referenceValue);
return this.createReference(resourcePath.relativeName);
}
case 'arrayValue': {
const array = [];
if (Array.isArray(proto.arrayValue.values)) {
for (const value of proto.arrayValue.values) {
array.push(this.decodeValue(value));
}
}
return array;
}
case 'nullValue': {
return null;
}
case 'mapValue': {
const obj = {};
const fields = proto.mapValue.fields;
if (fields) {
for (const prop of Object.keys(fields)) {
obj[prop] = this.decodeValue(fields[prop]);
}
}
return obj;
}
case 'geoPointValue': {
return geo_point_1.GeoPoint.fromProto(proto.geoPointValue);
}
case 'bytesValue': {
return proto.bytesValue;
}
default: {
throw new Error('Cannot decode type from Firestore Value: ' + JSON.stringify(proto));
}
}
}
}
exports.Serializer = Serializer;
/**
* Validates a JavaScript value for usage as a Firestore value.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value JavaScript value to validate.
* @param desc A description of the expected type.
* @param path The field path to validate.
* @param options Validation options
* @param level The current depth of the traversal. This is used to decide
* whether deletes are allowed in conjunction with `allowDeletes: root`.
* @param inArray Whether we are inside an array.
* @throws when the object is invalid.
*/
function validateUserInput(arg, value, desc, options, path, level, inArray) {
if (path && path.size > MAX_DEPTH) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Input object is deeper than ${MAX_DEPTH} levels or contains a cycle.`);
}
options = options || {};
level = level || 0;
inArray = inArray || false;
const fieldPathMessage = path ? ` (found in field "${path}")` : '';
if (Array.isArray(value)) {
for (let i = 0; i < value.length; ++i) {
validateUserInput(arg, value[i], desc, options, path ? path.append(String(i)) : new path_1.FieldPath(String(i)), level + 1,
/* inArray= */ true);
}
}
else if (util_1.isPlainObject(value)) {
for (const prop of Object.keys(value)) {
validateUserInput(arg, value[prop], desc, options, path ? path.append(new path_1.FieldPath(prop)) : new path_1.FieldPath(prop), level + 1, inArray);
}
}
else if (value === undefined) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}.`);
}
else if (value instanceof field_value_2.DeleteTransform) {
if (inArray) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`);
}
else if ((options.allowDeletes === 'root' && level !== 0) ||
options.allowDeletes === 'none') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() must appear at the top-level and can only be used in update() or set() with {merge:true}${fieldPathMessage}.`);
}
}
else if (value instanceof field_value_1.FieldTransform) {
if (inArray) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`);
}
else if (!options.allowTransforms) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() can only be used in set(), create() or update()${fieldPathMessage}.`);
}
}
else if (value instanceof path_1.FieldPath) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Cannot use object of type "FieldPath" as a Firestore value${fieldPathMessage}.`);
}
else if (value instanceof index_1.DocumentReference) {
// Ok.
}
else if (value instanceof geo_point_1.GeoPoint) {
// Ok.
}
else if (value instanceof timestamp_1.Timestamp || value instanceof Date) {
// Ok.
}
else if (isMomentJsType(value)) {
// Ok.
}
else if (value instanceof Buffer || value instanceof Uint8Array) {
// Ok.
}
else if (value === null) {
// Ok.
}
else if (typeof value === 'object') {
throw new Error(validate_1.customObjectMessage(arg, value, path));
}
}
exports.validateUserInput = validateUserInput;
/**
* Returns true if value is a MomentJs date object.
* @private
*/
function isMomentJsType(value) {
return (typeof value === 'object' &&
value !== null &&
value.constructor &&
value.constructor.name === 'Moment' &&
typeof value.toDate === 'function');
}
//# sourceMappingURL=serializer.js.map

View File

@ -0,0 +1,178 @@
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { google } from '../protos/firestore_v1_proto_api';
import api = google.firestore.v1;
/**
* A Timestamp represents a point in time independent of any time zone or
* calendar, represented as seconds and fractions of seconds at nanosecond
* resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian
* Calendar which extends the Gregorian calendar backwards to year one. It is
* encoded assuming all minutes are 60 seconds long, i.e. leap seconds are
* "smeared" so that no leap second table is needed for interpretation. Range is
* from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
*
* @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto
*/
export declare class Timestamp {
private readonly _seconds;
private readonly _nanoseconds;
/**
* Creates a new timestamp with the current date, with millisecond precision.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ updateTime:Firestore.Timestamp.now() });
*
* @return {Timestamp} A new `Timestamp` representing the current date.
*/
static now(): Timestamp;
/**
* Creates a new timestamp from the given date.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* let date = Date.parse('01 Jan 2000 00:00:00 GMT');
* documentRef.set({ startTime:Firestore.Timestamp.fromDate(date) });
*
* @param {Date} date The date to initialize the `Timestamp` from.
* @return {Timestamp} A new `Timestamp` representing the same point in time
* as the given date.
*/
static fromDate(date: Date): Timestamp;
/**
* Creates a new timestamp from the given number of milliseconds.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ startTime:Firestore.Timestamp.fromMillis(42) });
*
* @param {number} milliseconds Number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
* @return {Timestamp} A new `Timestamp` representing the same point in time
* as the given number of milliseconds.
*/
static fromMillis(milliseconds: number): Timestamp;
/**
* Generates a `Timestamp` object from a Timestamp proto.
*
* @private
* @param {Object} timestamp The `Timestamp` Protobuf object.
*/
static fromProto(timestamp: google.protobuf.ITimestamp): Timestamp;
/**
* Creates a new timestamp.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ startTime:new Firestore.Timestamp(42, 0) });
*
* @param {number} seconds The number of seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
* @param {number} nanoseconds The non-negative fractions of a second at
* nanosecond resolution. Negative second values with fractions must still
* have non-negative nanoseconds values that count forward in time. Must be
* from 0 to 999,999,999 inclusive.
*/
constructor(seconds: number, nanoseconds: number);
/**
* The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* let updated = snap.updateTime;
* console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`);
* });
*
* @type {number}
*/
readonly seconds: number;
/**
* The non-negative fractions of a second at nanosecond resolution.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* let updated = snap.updateTime;
* console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`);
* });
*
* @type {number}
*/
readonly nanoseconds: number;
/**
* Returns a new `Date` corresponding to this timestamp. This may lose
* precision.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* console.log(`Document updated at: ${snap.updateTime.toDate()}`);
* });
*
* @return {Date} JavaScript `Date` object representing the same point in time
* as this `Timestamp`, with millisecond precision.
*/
toDate(): Date;
/**
* Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* let startTime = snap.get('startTime');
* let endTime = snap.get('endTime');
* console.log(`Duration: ${endTime - startTime}`);
* });
*
* @return {number} The point in time corresponding to this timestamp,
* represented as the number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
*/
toMillis(): number;
/**
* Returns 'true' if this `Timestamp` is equal to the provided one.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* if (snap.createTime.isEqual(snap.updateTime)) {
* console.log('Document is in its initial state.');
* }
* });
*
* @param {any} other The `Timestamp` to compare against.
* @return {boolean} 'true' if this `Timestamp` is equal to the provided one.
*/
isEqual(other: Timestamp): boolean;
/**
* Generates the Protobuf `Timestamp` object for this timestamp.
*
* @private
* @returns {Object} The `Timestamp` Protobuf object.
*/
toProto(): api.IValue;
}

View File

@ -0,0 +1,225 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("./validate");
/*!
* Number of nanoseconds in a millisecond.
*
* @type {number}
*/
const MS_TO_NANOS = 1000000;
/**
* A Timestamp represents a point in time independent of any time zone or
* calendar, represented as seconds and fractions of seconds at nanosecond
* resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian
* Calendar which extends the Gregorian calendar backwards to year one. It is
* encoded assuming all minutes are 60 seconds long, i.e. leap seconds are
* "smeared" so that no leap second table is needed for interpretation. Range is
* from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
*
* @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto
*/
class Timestamp {
/**
* Creates a new timestamp.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ startTime:new Firestore.Timestamp(42, 0) });
*
* @param {number} seconds The number of seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
* @param {number} nanoseconds The non-negative fractions of a second at
* nanosecond resolution. Negative second values with fractions must still
* have non-negative nanoseconds values that count forward in time. Must be
* from 0 to 999,999,999 inclusive.
*/
constructor(seconds, nanoseconds) {
validate_1.validateInteger('seconds', seconds);
validate_1.validateInteger('nanoseconds', nanoseconds, {
minValue: 0,
maxValue: 999999999,
});
this._seconds = seconds;
this._nanoseconds = nanoseconds;
}
/**
* Creates a new timestamp with the current date, with millisecond precision.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ updateTime:Firestore.Timestamp.now() });
*
* @return {Timestamp} A new `Timestamp` representing the current date.
*/
static now() {
return Timestamp.fromMillis(Date.now());
}
/**
* Creates a new timestamp from the given date.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* let date = Date.parse('01 Jan 2000 00:00:00 GMT');
* documentRef.set({ startTime:Firestore.Timestamp.fromDate(date) });
*
* @param {Date} date The date to initialize the `Timestamp` from.
* @return {Timestamp} A new `Timestamp` representing the same point in time
* as the given date.
*/
static fromDate(date) {
return Timestamp.fromMillis(date.getTime());
}
/**
* Creates a new timestamp from the given number of milliseconds.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ startTime:Firestore.Timestamp.fromMillis(42) });
*
* @param {number} milliseconds Number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
* @return {Timestamp} A new `Timestamp` representing the same point in time
* as the given number of milliseconds.
*/
static fromMillis(milliseconds) {
const seconds = Math.floor(milliseconds / 1000);
const nanos = (milliseconds - seconds * 1000) * MS_TO_NANOS;
return new Timestamp(seconds, nanos);
}
/**
* Generates a `Timestamp` object from a Timestamp proto.
*
* @private
* @param {Object} timestamp The `Timestamp` Protobuf object.
*/
static fromProto(timestamp) {
return new Timestamp(Number(timestamp.seconds || 0), Number(timestamp.nanos || 0));
}
/**
* The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* let updated = snap.updateTime;
* console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`);
* });
*
* @type {number}
*/
get seconds() {
return this._seconds;
}
/**
* The non-negative fractions of a second at nanosecond resolution.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* let updated = snap.updateTime;
* console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`);
* });
*
* @type {number}
*/
get nanoseconds() {
return this._nanoseconds;
}
/**
* Returns a new `Date` corresponding to this timestamp. This may lose
* precision.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* console.log(`Document updated at: ${snap.updateTime.toDate()}`);
* });
*
* @return {Date} JavaScript `Date` object representing the same point in time
* as this `Timestamp`, with millisecond precision.
*/
toDate() {
return new Date(this._seconds * 1000 + Math.round(this._nanoseconds / MS_TO_NANOS));
}
/**
* Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* let startTime = snap.get('startTime');
* let endTime = snap.get('endTime');
* console.log(`Duration: ${endTime - startTime}`);
* });
*
* @return {number} The point in time corresponding to this timestamp,
* represented as the number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
*/
toMillis() {
return this._seconds * 1000 + Math.floor(this._nanoseconds / MS_TO_NANOS);
}
/**
* Returns 'true' if this `Timestamp` is equal to the provided one.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* if (snap.createTime.isEqual(snap.updateTime)) {
* console.log('Document is in its initial state.');
* }
* });
*
* @param {any} other The `Timestamp` to compare against.
* @return {boolean} 'true' if this `Timestamp` is equal to the provided one.
*/
isEqual(other) {
return (this === other ||
(other instanceof Timestamp &&
this._seconds === other.seconds &&
this._nanoseconds === other.nanoseconds));
}
/**
* Generates the Protobuf `Timestamp` object for this timestamp.
*
* @private
* @returns {Object} The `Timestamp` Protobuf object.
*/
toProto() {
const timestamp = {};
if (this.seconds) {
timestamp.seconds = this.seconds;
}
if (this.nanoseconds) {
timestamp.nanos = this.nanoseconds;
}
return { timestampValue: timestamp };
}
}
exports.Timestamp = Timestamp;
//# sourceMappingURL=timestamp.js.map

View File

@ -0,0 +1,238 @@
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { DocumentSnapshot, Precondition } from './document';
import { Firestore } from './index';
import { FieldPath } from './path';
import { DocumentReference, Query, QuerySnapshot } from './reference';
import { Precondition as PublicPrecondition, ReadOptions, SetOptions, UpdateData } from './types';
/**
* A reference to a transaction.
*
* The Transaction object passed to a transaction's updateFunction provides
* the methods to read and write data within the transaction context. See
* [runTransaction()]{@link Firestore#runTransaction}.
*
* @class
*/
export declare class Transaction {
private _firestore;
private _writeBatch;
private _requestTag;
private _transactionId?;
/**
* @hideconstructor
*
* @param firestore The Firestore Database client.
* @param requestTag A unique client-assigned identifier for the scope of
* this transaction.
*/
constructor(firestore: Firestore, requestTag: string);
/**
* Retrieves a query result. Holds a pessimistic lock on all returned
* documents.
*
* @param {Query} query A query to execute.
* @return {Promise<QuerySnapshot>} A QuerySnapshot for the retrieved data.
*/
get<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
/**
* Reads the document referenced by the provided `DocumentReference.`
* Holds a pessimistic lock on the returned document.
*
* @param {DocumentReference} documentRef A reference to the document to be read.
* @return {Promise<DocumentSnapshot>} A DocumentSnapshot for the read data.
*/
get<T>(documentRef: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
/**
* Retrieves multiple documents from Firestore. Holds a pessimistic lock on
* all returned documents.
*
* The first argument is required and must be of type `DocumentReference`
* followed by any additional `DocumentReference` documents. If used, the
* optional `ReadOptions` must be the last argument.
*
* @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The
* `DocumentReferences` to receive, followed by an optional field mask.
* @returns {Promise<Array.<DocumentSnapshot>>} A Promise that
* contains an array with the resulting document snapshots.
*
* @example
* let firstDoc = firestore.doc('col/doc1');
* let secondDoc = firestore.doc('col/doc2');
* let resultDoc = firestore.doc('col/doc3');
*
* firestore.runTransaction(transaction => {
* return transaction.getAll(firstDoc, secondDoc).then(docs => {
* transaction.set(resultDoc, {
* sum: docs[0].get('count') + docs[1].get('count')
* });
* });
* });
*/
getAll<T>(...documentRefsOrReadOptions: Array<DocumentReference<T> | ReadOptions>): Promise<Array<DocumentSnapshot<T>>>;
/**
* Create the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. The operation will
* fail the transaction if a document exists at the specified location.
*
* @param {DocumentReference} documentRef A reference to the document to be
* created.
* @param {DocumentData} data The object data to serialize as the document.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (!doc.exists) {
* transaction.create(documentRef, { foo: 'bar' });
* }
* });
* });
*/
create<T>(documentRef: DocumentReference<T>, data: T): Transaction;
/**
* Writes to the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document
* does not exist yet, it will be created. If you pass
* [SetOptions]{@link SetOptions}, the provided data can be merged into the
* existing document.
*
* @param {DocumentReference} documentRef A reference to the document to be
* set.
* @param {T} data The object to serialize as the document.
* @param {SetOptions=} options An object to configure the set behavior.
* @param {boolean=} options.merge - If true, set() merges the values
* specified in its data argument. Fields omitted from this set() call
* remain untouched.
* @param {Array.<string|FieldPath>=} options.mergeFields - If provided,
* set() only replaces the specified field paths. Any field path that is not
* specified is ignored and remains untouched.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* transaction.set(documentRef, { foo: 'bar' });
* return Promise.resolve();
* });
*/
set<T>(documentRef: DocumentReference<T>, data: T, options?: SetOptions): Transaction;
/**
* Updates fields in the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. The update will
* fail if applied to a document that does not exist.
*
* The update() method accepts either an object with field paths encoded as
* keys and field values encoded as values, or a variable number of arguments
* that alternate between field paths and field values. Nested fields can be
* updated by providing dot-separated field path strings or by providing
* FieldPath objects.
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {DocumentReference} documentRef A reference to the document to be
* updated.
* @param {UpdateData|string|FieldPath} dataOrField An object
* containing the fields and values with which to update the document
* or the path of the first field to update.
* @param {
* ...(Precondition|*|string|FieldPath)} preconditionOrValues -
* An alternating list of field paths and values to update or a Precondition
* to to enforce on this update.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (doc.exists) {
* transaction.update(documentRef, { count: doc.get('count') + 1 });
* } else {
* transaction.create(documentRef, { count: 1 });
* }
* });
* });
*/
update<T>(documentRef: DocumentReference<T>, dataOrField: UpdateData | string | FieldPath, ...preconditionOrValues: Array<Precondition | unknown | string | FieldPath>): Transaction;
/**
* Deletes the document referred to by the provided [DocumentReference]
* {@link DocumentReference}.
*
* @param {DocumentReference} documentRef A reference to the document to be
* deleted.
* @param {Precondition=} precondition A precondition to enforce for this
* delete.
* @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
* document was last updated at lastUpdateTime. Fails the transaction if the
* document doesn't exist or was last updated at a different time.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* transaction.delete(documentRef);
* return Promise.resolve();
* });
*/
delete<T>(documentRef: DocumentReference<T>, precondition?: PublicPrecondition): this;
/**
* Starts a transaction and obtains the transaction id from the server.
*
* @private
*/
begin(): Promise<void>;
/**
* Commits all queued-up changes in this transaction and releases all locks.
*
* @private
*/
commit(): Promise<void>;
/**
* Releases all locks and rolls back this transaction.
*
* @private
*/
rollback(): Promise<void>;
/**
* Executes `updateFunction()` and commits the transaction with retry.
*
* @private
* @param updateFunction The user function to execute within the transaction
* context.
* @param requestTag A unique client-assigned identifier for the scope of
* this transaction.
* @param maxAttempts The maximum number of attempts for this transaction.
*/
runTransaction<T>(updateFunction: (transaction: Transaction) => Promise<T>, maxAttempts: number): Promise<T>;
}
/**
* Parses the arguments for the `getAll()` call supported by both the Firestore
* and Transaction class.
*
* @private
* @param documentRefsOrReadOptions An array of document references followed by
* an optional ReadOptions object.
*/
export declare function parseGetAllArguments<T>(documentRefsOrReadOptions: Array<DocumentReference<T> | ReadOptions>): {
documents: Array<DocumentReference<T>>;
fieldMask: FieldPath[] | null;
};

View File

@ -0,0 +1,417 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const google_gax_1 = require("google-gax");
const logger_1 = require("./logger");
const path_1 = require("./path");
const reference_1 = require("./reference");
const util_1 = require("./util");
const validate_1 = require("./validate");
/*!
* Error message for transactional reads that were executed after performing
* writes.
*/
const READ_AFTER_WRITE_ERROR_MSG = 'Firestore transactions require all reads to be executed before all writes.';
/**
* A reference to a transaction.
*
* The Transaction object passed to a transaction's updateFunction provides
* the methods to read and write data within the transaction context. See
* [runTransaction()]{@link Firestore#runTransaction}.
*
* @class
*/
class Transaction {
/**
* @hideconstructor
*
* @param firestore The Firestore Database client.
* @param requestTag A unique client-assigned identifier for the scope of
* this transaction.
*/
constructor(firestore, requestTag) {
this._firestore = firestore;
this._writeBatch = firestore.batch();
this._requestTag = requestTag;
}
/**
* Retrieve a document or a query result from the database. Holds a
* pessimistic lock on all returned documents.
*
* @param {DocumentReference|Query} refOrQuery The document or query to
* return.
* @returns {Promise} A Promise that resolves with a DocumentSnapshot or
* QuerySnapshot for the returned documents.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (doc.exists) {
* transaction.update(documentRef, { count: doc.get('count') + 1 });
* } else {
* transaction.create(documentRef, { count: 1 });
* }
* });
* });
*/
get(refOrQuery) {
if (!this._writeBatch.isEmpty) {
throw new Error(READ_AFTER_WRITE_ERROR_MSG);
}
if (refOrQuery instanceof reference_1.DocumentReference) {
return this._firestore
.getAll_([refOrQuery],
/* fieldMask= */ null, this._requestTag, this._transactionId)
.then(res => {
return Promise.resolve(res[0]);
});
}
if (refOrQuery instanceof reference_1.Query) {
return refOrQuery._get(this._transactionId);
}
throw new Error('Value for argument "refOrQuery" must be a DocumentReference or a Query.');
}
/**
* Retrieves multiple documents from Firestore. Holds a pessimistic lock on
* all returned documents.
*
* The first argument is required and must be of type `DocumentReference`
* followed by any additional `DocumentReference` documents. If used, the
* optional `ReadOptions` must be the last argument.
*
* @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The
* `DocumentReferences` to receive, followed by an optional field mask.
* @returns {Promise<Array.<DocumentSnapshot>>} A Promise that
* contains an array with the resulting document snapshots.
*
* @example
* let firstDoc = firestore.doc('col/doc1');
* let secondDoc = firestore.doc('col/doc2');
* let resultDoc = firestore.doc('col/doc3');
*
* firestore.runTransaction(transaction => {
* return transaction.getAll(firstDoc, secondDoc).then(docs => {
* transaction.set(resultDoc, {
* sum: docs[0].get('count') + docs[1].get('count')
* });
* });
* });
*/
getAll(...documentRefsOrReadOptions) {
if (!this._writeBatch.isEmpty) {
throw new Error(READ_AFTER_WRITE_ERROR_MSG);
}
validate_1.validateMinNumberOfArguments('Transaction.getAll', arguments, 1);
const { documents, fieldMask } = parseGetAllArguments(documentRefsOrReadOptions);
return this._firestore.getAll_(documents, fieldMask, this._requestTag, this._transactionId);
}
/**
* Create the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. The operation will
* fail the transaction if a document exists at the specified location.
*
* @param {DocumentReference} documentRef A reference to the document to be
* created.
* @param {DocumentData} data The object data to serialize as the document.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (!doc.exists) {
* transaction.create(documentRef, { foo: 'bar' });
* }
* });
* });
*/
create(documentRef, data) {
this._writeBatch.create(documentRef, data);
return this;
}
/**
* Writes to the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document
* does not exist yet, it will be created. If you pass
* [SetOptions]{@link SetOptions}, the provided data can be merged into the
* existing document.
*
* @param {DocumentReference} documentRef A reference to the document to be
* set.
* @param {T} data The object to serialize as the document.
* @param {SetOptions=} options An object to configure the set behavior.
* @param {boolean=} options.merge - If true, set() merges the values
* specified in its data argument. Fields omitted from this set() call
* remain untouched.
* @param {Array.<string|FieldPath>=} options.mergeFields - If provided,
* set() only replaces the specified field paths. Any field path that is not
* specified is ignored and remains untouched.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* transaction.set(documentRef, { foo: 'bar' });
* return Promise.resolve();
* });
*/
set(documentRef, data, options) {
this._writeBatch.set(documentRef, data, options);
return this;
}
/**
* Updates fields in the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. The update will
* fail if applied to a document that does not exist.
*
* The update() method accepts either an object with field paths encoded as
* keys and field values encoded as values, or a variable number of arguments
* that alternate between field paths and field values. Nested fields can be
* updated by providing dot-separated field path strings or by providing
* FieldPath objects.
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {DocumentReference} documentRef A reference to the document to be
* updated.
* @param {UpdateData|string|FieldPath} dataOrField An object
* containing the fields and values with which to update the document
* or the path of the first field to update.
* @param {
* ...(Precondition|*|string|FieldPath)} preconditionOrValues -
* An alternating list of field paths and values to update or a Precondition
* to to enforce on this update.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (doc.exists) {
* transaction.update(documentRef, { count: doc.get('count') + 1 });
* } else {
* transaction.create(documentRef, { count: 1 });
* }
* });
* });
*/
update(documentRef, dataOrField, ...preconditionOrValues) {
validate_1.validateMinNumberOfArguments('Transaction.update', arguments, 2);
this._writeBatch.update(documentRef, dataOrField, ...preconditionOrValues);
return this;
}
/**
* Deletes the document referred to by the provided [DocumentReference]
* {@link DocumentReference}.
*
* @param {DocumentReference} documentRef A reference to the document to be
* deleted.
* @param {Precondition=} precondition A precondition to enforce for this
* delete.
* @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
* document was last updated at lastUpdateTime. Fails the transaction if the
* document doesn't exist or was last updated at a different time.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* transaction.delete(documentRef);
* return Promise.resolve();
* });
*/
delete(documentRef, precondition) {
this._writeBatch.delete(documentRef, precondition);
return this;
}
/**
* Starts a transaction and obtains the transaction id from the server.
*
* @private
*/
begin() {
const request = {
database: this._firestore.formattedName,
};
if (this._transactionId) {
request.options = {
readWrite: {
retryTransaction: this._transactionId,
},
};
}
return this._firestore
.request('beginTransaction', request, this._requestTag)
.then(resp => {
this._transactionId = resp.transaction;
});
}
/**
* Commits all queued-up changes in this transaction and releases all locks.
*
* @private
*/
commit() {
return this._writeBatch
.commit_({
transactionId: this._transactionId,
requestTag: this._requestTag,
})
.then(() => { });
}
/**
* Releases all locks and rolls back this transaction.
*
* @private
*/
rollback() {
const request = {
database: this._firestore.formattedName,
transaction: this._transactionId,
};
return this._firestore.request('rollback', request, this._requestTag);
}
/**
* Executes `updateFunction()` and commits the transaction with retry.
*
* @private
* @param updateFunction The user function to execute within the transaction
* context.
* @param requestTag A unique client-assigned identifier for the scope of
* this transaction.
* @param maxAttempts The maximum number of attempts for this transaction.
*/
async runTransaction(updateFunction, maxAttempts) {
let result;
let lastError = undefined;
for (let attempt = 0; attempt < maxAttempts; ++attempt) {
if (lastError) {
logger_1.logger('Firestore.runTransaction', this._requestTag, `Retrying transaction after error:`, lastError);
}
await this.begin();
try {
const promise = updateFunction(this);
if (!(promise instanceof Promise)) {
throw new Error('You must return a Promise in your transaction()-callback.');
}
result = await promise;
}
catch (err) {
logger_1.logger('Firestore.runTransaction', this._requestTag, 'Rolling back transaction after callback error:', err);
await this.rollback();
if (isRetryableTransactionError(err)) {
lastError = err;
continue; // Retry full transaction
}
else {
return Promise.reject(err); // Callback failed w/ non-retryable error
}
}
try {
await this.commit();
return result; // Success
}
catch (err) {
lastError = err;
this._writeBatch._reset();
}
}
logger_1.logger('Firestore.runTransaction', this._requestTag, 'Transaction not eligible for retry, returning error: %s', lastError);
return Promise.reject(lastError);
}
}
exports.Transaction = Transaction;
/**
* Parses the arguments for the `getAll()` call supported by both the Firestore
* and Transaction class.
*
* @private
* @param documentRefsOrReadOptions An array of document references followed by
* an optional ReadOptions object.
*/
function parseGetAllArguments(documentRefsOrReadOptions) {
let documents;
let readOptions = undefined;
if (Array.isArray(documentRefsOrReadOptions[0])) {
throw new Error('getAll() no longer accepts an array as its first argument. ' +
'Please unpack your array and call getAll() with individual arguments.');
}
if (documentRefsOrReadOptions.length > 0 &&
util_1.isPlainObject(documentRefsOrReadOptions[documentRefsOrReadOptions.length - 1])) {
readOptions = documentRefsOrReadOptions.pop();
documents = documentRefsOrReadOptions;
}
else {
documents = documentRefsOrReadOptions;
}
for (let i = 0; i < documents.length; ++i) {
reference_1.validateDocumentReference(i, documents[i]);
}
validateReadOptions('options', readOptions, { optional: true });
const fieldMask = readOptions && readOptions.fieldMask
? readOptions.fieldMask.map(fieldPath => path_1.FieldPath.fromArgument(fieldPath))
: null;
return { fieldMask, documents };
}
exports.parseGetAllArguments = parseGetAllArguments;
/**
* Validates the use of 'options' as ReadOptions and enforces that 'fieldMask'
* is an array of strings or field paths.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the ReadOptions can be omitted.
*/
function validateReadOptions(arg, value, options) {
if (!validate_1.validateOptional(value, options)) {
if (!util_1.isObject(value)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'read option')} Input is not an object.'`);
}
const options = value;
if (options.fieldMask !== undefined) {
if (!Array.isArray(options.fieldMask)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'read option')} "fieldMask" is not an array.`);
}
for (let i = 0; i < options.fieldMask.length; ++i) {
try {
path_1.validateFieldPath(i, options.fieldMask[i]);
}
catch (err) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'read option')} "fieldMask" is not valid: ${err.message}`);
}
}
}
}
}
function isRetryableTransactionError(error) {
if (error instanceof google_gax_1.GoogleError || 'code' in error) {
// In transactions, the backend returns code ABORTED for reads that fail
// with contention. These errors should be retried for both GoogleError
// and GoogleError-alike errors (in case the prototype hierarchy gets
// stripped somewhere).
return error.code === google_gax_1.Status.ABORTED;
}
return false;
}
//# sourceMappingURL=transaction.js.map

View File

@ -0,0 +1,245 @@
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference types="node" />
import { CallOptions } from 'google-gax';
import { Duplex } from 'stream';
import { google } from '../protos/firestore_v1_proto_api';
import { FieldPath } from './path';
import { Timestamp } from './timestamp';
import api = google.firestore.v1;
/**
* A map in the format of the Proto API
*/
export interface ApiMapValue {
[k: string]: google.firestore.v1.IValue;
}
/**
* The subset of methods we use from FirestoreClient.
*
* We don't depend on the actual Gapic client to avoid loading the GAX stack at
* module initialization time.
*/
export interface GapicClient {
getProjectId(): Promise<string>;
beginTransaction(request: api.IBeginTransactionRequest, options?: CallOptions): Promise<[api.IBeginTransactionResponse, unknown, unknown]>;
commit(request: api.ICommitRequest, options?: CallOptions): Promise<[api.ICommitResponse, unknown, unknown]>;
rollback(request: api.IRollbackRequest, options?: CallOptions): Promise<[google.protobuf.IEmpty, unknown, unknown]>;
batchGetDocuments(request?: api.IBatchGetDocumentsRequest, options?: CallOptions): Duplex;
runQuery(request?: api.IRunQueryRequest, options?: CallOptions): Duplex;
listDocuments(request: api.IListDocumentsRequest, options?: CallOptions): Promise<[api.IDocument[], unknown, unknown]>;
listCollectionIds(request: api.IListCollectionIdsRequest, options?: CallOptions): Promise<[string[], unknown, unknown]>;
listen(options?: CallOptions): Duplex;
close(): Promise<void>;
}
/** Request/response methods used in the Firestore SDK. */
export declare type FirestoreUnaryMethod = 'listDocuments' | 'listCollectionIds' | 'rollback' | 'beginTransaction' | 'commit';
/** Streaming methods used in the Firestore SDK. */
export declare type FirestoreStreamingMethod = 'listen' | 'runQuery' | 'batchGetDocuments';
/** Type signature for the unary methods in the GAPIC layer. */
export declare type UnaryMethod<Req, Resp> = (request: Req, callOptions: CallOptions) => Promise<[Resp, unknown, unknown]>;
export declare type RBTree = any;
/**
* Converter used by `withConverter()` to transform user objects of type T
* into Firestore data.
*
* Using the converter allows you to specify generic type arguments when
* storing and retrieving objects from Firestore.
*
* @example
* class Post {
* constructor(readonly title: string, readonly author: string) {}
*
* toString(): string {
* return this.title + ', by ' + this.author;
* }
* }
*
* const postConverter = {
* toFirestore(post: Post): FirebaseFirestore.DocumentData {
* return {title: post.title, author: post.author};
* },
* fromFirestore(
* data: FirebaseFirestore.DocumentData
* ): Post {
* return new Post(data.title, data.author);
* }
* };
*
* const postSnap = await Firestore()
* .collection('posts')
* .withConverter(postConverter)
* .doc().get();
* const post = postSnap.data();
* if (post !== undefined) {
* post.title; // string
* post.toString(); // Should be defined
* post.someNonExistentProperty; // TS error
* }
*/
export interface FirestoreDataConverter<T> {
/**
* Called by the Firestore SDK to convert a custom model object of type T
* into a plain Javascript object (suitable for writing directly to the
* Firestore database).
*/
toFirestore(modelObject: T): DocumentData;
/**
* Called by the Firestore SDK to convert Firestore data into an object of
* type T.
*/
fromFirestore(data: DocumentData): T;
}
/**
* A default converter to use when none is provided.
* @private
*/
export declare const defaultConverter: FirestoreDataConverter<DocumentData>;
/**
* Settings used to directly configure a `Firestore` instance.
*/
export interface Settings {
/**
* The Firestore Project ID. Can be omitted in environments that support
* `Application Default Credentials` {@see https://cloud.google.com/docs/authentication}
*/
projectId?: string;
/** The host to connect to. */
host?: string;
/**
* Local file containing the Service Account credentials. Can be omitted
* in environments that support `Application Default Credentials`
* {@see https://cloud.google.com/docs/authentication}
*/
keyFilename?: string;
/**
* The 'client_email' and 'private_key' properties of the service account
* to use with your Firestore project. Can be omitted in environments that
* support {@link https://cloud.google.com/docs/authentication Application
* Default Credentials}. If your credentials are stored in a JSON file, you
* can specify a `keyFilename` instead.
*/
credentials?: {
client_email?: string;
private_key?: string;
};
/** Whether to use SSL when connecting. */
ssl?: boolean;
/**
* The maximum number of idle GRPC channels to keep. A smaller number of idle
* channels reduces memory usage but increases request latency for clients
* with fluctuating request rates. If set to 0, shuts down all GRPC channels
* when the client becomes idle. Defaults to 1.
*/
maxIdleChannels?: number;
[key: string]: any;
}
/**
* Document data (for use with `DocumentReference.set()`) consists of fields
* mapped to values.
*/
export interface DocumentData {
[field: string]: any;
}
/**
* Update data (for use with `DocumentReference.update()`) consists of field
* paths (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots
* reference nested fields within the document.
*/
export interface UpdateData {
[fieldPath: string]: unknown;
}
/**
* Update data that has been resolved to a mapping of FieldPaths to values.
*/
export declare type UpdateMap = Map<FieldPath, unknown>;
/**
* The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc'
* (descending or ascending).
*/
export declare type OrderByDirection = 'desc' | 'asc';
/**
* Filter conditions in a `Query.where()` clause are specified using the
* strings '<', '<=', '==', '>=', '>','array-contains', 'in', and
* 'array-contains-any'.
*/
export declare type WhereFilterOp = '<' | '<=' | '==' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any';
/**
* An options object that configures conditional behavior of `update()` and
* `delete()` calls in `DocumentReference`, `WriteBatch`, and `Transaction`.
* Using Preconditions, these calls can be restricted to only apply to
* documents that match the specified restrictions.
*/
export interface Precondition {
/**
* If set, the last update time to enforce.
*/
readonly lastUpdateTime?: Timestamp;
}
/**
* An options object that configures the behavior of `set()` calls in
* `DocumentReference`, `WriteBatch` and `Transaction`. These calls can be
* configured to perform granular merges instead of overwriting the target
* documents in their entirety.
*/
export interface SetOptions {
/**
* Changes the behavior of a set() call to only replace the values specified
* in its data argument. Fields omitted from the set() call remain
* untouched.
*/
readonly merge?: boolean;
/**
* Changes the behavior of set() calls to only replace the specified field
* paths. Any field path that is not specified is ignored and remains
* untouched.
*
* It is an error to pass a SetOptions object to a set() call that is
* missing a value for any of the fields specified here.
*/
readonly mergeFields?: Array<string | FieldPath>;
}
/**
* An options object that can be used to configure the behavior of `getAll()`
* calls. By providing a `fieldMask`, these calls can be configured to only
* return a subset of fields.
*/
export interface ReadOptions {
/**
* Specifies the set of fields to return and reduces the amount of data
* transmitted by the backend.
*
* Adding a field mask does not filter results. Documents do not need to
* contain values for all the fields in the mask to be part of the result set.
*/
readonly fieldMask?: Array<string | FieldPath>;
}
/**
* Internal user data validation options.
* @private
*/
export interface ValidationOptions {
/** At what level field deletes are supported. */
allowDeletes: 'none' | 'root' | 'all';
/** Whether server transforms are supported. */
allowTransforms: boolean;
}
/**
* A Firestore Proto value in ProtoJs format.
* @private
*/
export interface ProtobufJsValue extends api.IValue {
valueType?: string;
}

View File

@ -0,0 +1,30 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A default converter to use when none is provided.
* @private
*/
exports.defaultConverter = {
toFirestore(modelObject) {
return modelObject;
},
fromFirestore(data) {
return data;
},
};
//# sourceMappingURL=types.js.map

View File

@ -0,0 +1,81 @@
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { GoogleError, ServiceConfig } from 'google-gax';
import { DocumentData } from './types';
/**
* A Promise implementation that supports deferred resolution.
* @private
*/
export declare class Deferred<R> {
promise: Promise<R>;
resolve: (value?: R | Promise<R>) => void;
reject: (reason?: Error) => void;
constructor();
}
/**
* Generate a unique client-side identifier.
*
* Used for the creation of new documents.
*
* @private
* @returns {string} A unique 20-character wide identifier.
*/
export declare function autoId(): string;
/**
* Generate a short and semi-random client-side identifier.
*
* Used for the creation of request tags.
*
* @private
* @returns {string} A random 5-character wide identifier.
*/
export declare function requestTag(): string;
/**
* Determines whether `value` is a JavaScript object.
*
* @private
*/
export declare function isObject(value: unknown): value is {
[k: string]: unknown;
};
/**
* Verifies that 'obj' is a plain JavaScript object that can be encoded as a
* 'Map' in Firestore.
*
* @private
* @param input The argument to verify.
* @returns 'true' if the input can be a treated as a plain object.
*/
export declare function isPlainObject(input: unknown): input is DocumentData;
/**
* Returns whether `value` has no custom properties.
*
* @private
*/
export declare function isEmpty(value: {}): boolean;
/**
* Determines whether `value` is a JavaScript function.
*
* @private
*/
export declare function isFunction(value: unknown): boolean;
/**
* Determines whether the provided error is considered permanent for the given
* RPC.
*
* @private
*/
export declare function isPermanentRpcError(err: GoogleError, methodName: string, config: ServiceConfig): boolean;

123
node_modules/@google-cloud/firestore/build/src/util.js generated vendored Normal file
View File

@ -0,0 +1,123 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const google_gax_1 = require("google-gax");
/**
* A Promise implementation that supports deferred resolution.
* @private
*/
class Deferred {
constructor() {
this.resolve = () => { };
this.reject = () => { };
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
exports.Deferred = Deferred;
/**
* Generate a unique client-side identifier.
*
* Used for the creation of new documents.
*
* @private
* @returns {string} A unique 20-character wide identifier.
*/
function autoId() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let autoId = '';
for (let i = 0; i < 20; i++) {
autoId += chars.charAt(Math.floor(Math.random() * chars.length));
}
return autoId;
}
exports.autoId = autoId;
/**
* Generate a short and semi-random client-side identifier.
*
* Used for the creation of request tags.
*
* @private
* @returns {string} A random 5-character wide identifier.
*/
function requestTag() {
return autoId().substr(0, 5);
}
exports.requestTag = requestTag;
/**
* Determines whether `value` is a JavaScript object.
*
* @private
*/
function isObject(value) {
return Object.prototype.toString.call(value) === '[object Object]';
}
exports.isObject = isObject;
/**
* Verifies that 'obj' is a plain JavaScript object that can be encoded as a
* 'Map' in Firestore.
*
* @private
* @param input The argument to verify.
* @returns 'true' if the input can be a treated as a plain object.
*/
function isPlainObject(input) {
return (isObject(input) &&
(Object.getPrototypeOf(input) === Object.prototype ||
Object.getPrototypeOf(input) === null ||
input.constructor.name === 'Object'));
}
exports.isPlainObject = isPlainObject;
/**
* Returns whether `value` has no custom properties.
*
* @private
*/
function isEmpty(value) {
return Object.keys(value).length === 0;
}
exports.isEmpty = isEmpty;
/**
* Determines whether `value` is a JavaScript function.
*
* @private
*/
function isFunction(value) {
return typeof value === 'function';
}
exports.isFunction = isFunction;
/**
* Determines whether the provided error is considered permanent for the given
* RPC.
*
* @private
*/
function isPermanentRpcError(err, methodName, config) {
if (err.code !== undefined) {
const serviceConfigName = methodName[0].toUpperCase() + methodName.slice(1);
const retryCodeNames = config.methods[serviceConfigName].retry_codes_name;
const retryCodes = config.retry_codes[retryCodeNames].map(errorName => google_gax_1.Status[errorName]);
return retryCodes.indexOf(err.code) === -1;
}
else {
return false;
}
}
exports.isPermanentRpcError = isPermanentRpcError;
//# sourceMappingURL=util.js.map

View File

@ -0,0 +1,303 @@
/// <reference types="node" />
import * as gax from 'google-gax';
import { Callback, ClientOptions, LROperation } from 'google-gax';
import { Transform } from 'stream';
import * as protosTypes from '../../protos/firestore_admin_v1_proto_api';
/**
* Operations are created by service `FirestoreAdmin`, but are accessed via
* service `google.longrunning.Operations`.
* @class
* @memberof v1
*/
export declare class FirestoreAdminClient {
private _descriptors;
private _innerApiCalls;
private _pathTemplates;
private _terminated;
auth: gax.GoogleAuth;
operationsClient: gax.OperationsClient;
firestoreAdminStub: Promise<{
[name: string]: Function;
}>;
/**
* Construct an instance of FirestoreAdminClient.
*
* @param {object} [options] - The configuration object. See the subsequent
* parameters for more details.
* @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://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
*/
constructor(opts?: ClientOptions);
/**
* The DNS address for this API service.
*/
static readonly servicePath: string;
/**
* The DNS address for this API service - same as servicePath(),
* exists for compatibility reasons.
*/
static readonly apiEndpoint: string;
/**
* The port for this API service.
*/
static readonly port: number;
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
*/
static readonly scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback: Callback<string, undefined, undefined>): void;
getIndex(request: protosTypes.google.firestore.admin.v1.IGetIndexRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.admin.v1.IIndex, protosTypes.google.firestore.admin.v1.IGetIndexRequest | undefined, {} | undefined]>;
getIndex(request: protosTypes.google.firestore.admin.v1.IGetIndexRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.admin.v1.IIndex, protosTypes.google.firestore.admin.v1.IGetIndexRequest | undefined, {} | undefined>): void;
deleteIndex(request: protosTypes.google.firestore.admin.v1.IDeleteIndexRequest, options?: gax.CallOptions): Promise<[protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.admin.v1.IDeleteIndexRequest | undefined, {} | undefined]>;
deleteIndex(request: protosTypes.google.firestore.admin.v1.IDeleteIndexRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.admin.v1.IDeleteIndexRequest | undefined, {} | undefined>): void;
getField(request: protosTypes.google.firestore.admin.v1.IGetFieldRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.admin.v1.IField, protosTypes.google.firestore.admin.v1.IGetFieldRequest | undefined, {} | undefined]>;
getField(request: protosTypes.google.firestore.admin.v1.IGetFieldRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.admin.v1.IField, protosTypes.google.firestore.admin.v1.IGetFieldRequest | undefined, {} | undefined>): void;
createIndex(request: protosTypes.google.firestore.admin.v1.ICreateIndexRequest, options?: gax.CallOptions): Promise<[LROperation<protosTypes.google.firestore.admin.v1.IIndex, protosTypes.google.firestore.admin.v1.IIndexOperationMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined]>;
createIndex(request: protosTypes.google.firestore.admin.v1.ICreateIndexRequest, options: gax.CallOptions, callback: Callback<LROperation<protosTypes.google.firestore.admin.v1.IIndex, protosTypes.google.firestore.admin.v1.IIndexOperationMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined>): void;
updateField(request: protosTypes.google.firestore.admin.v1.IUpdateFieldRequest, options?: gax.CallOptions): Promise<[LROperation<protosTypes.google.firestore.admin.v1.IField, protosTypes.google.firestore.admin.v1.IFieldOperationMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined]>;
updateField(request: protosTypes.google.firestore.admin.v1.IUpdateFieldRequest, options: gax.CallOptions, callback: Callback<LROperation<protosTypes.google.firestore.admin.v1.IField, protosTypes.google.firestore.admin.v1.IFieldOperationMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined>): void;
exportDocuments(request: protosTypes.google.firestore.admin.v1.IExportDocumentsRequest, options?: gax.CallOptions): Promise<[LROperation<protosTypes.google.firestore.admin.v1.IExportDocumentsResponse, protosTypes.google.firestore.admin.v1.IExportDocumentsMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined]>;
exportDocuments(request: protosTypes.google.firestore.admin.v1.IExportDocumentsRequest, options: gax.CallOptions, callback: Callback<LROperation<protosTypes.google.firestore.admin.v1.IExportDocumentsResponse, protosTypes.google.firestore.admin.v1.IExportDocumentsMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined>): void;
importDocuments(request: protosTypes.google.firestore.admin.v1.IImportDocumentsRequest, options?: gax.CallOptions): Promise<[LROperation<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.admin.v1.IImportDocumentsMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined]>;
importDocuments(request: protosTypes.google.firestore.admin.v1.IImportDocumentsRequest, options: gax.CallOptions, callback: Callback<LROperation<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.admin.v1.IImportDocumentsMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined>): void;
listIndexes(request: protosTypes.google.firestore.admin.v1.IListIndexesRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.admin.v1.IIndex[], protosTypes.google.firestore.admin.v1.IListIndexesRequest | null, protosTypes.google.firestore.admin.v1.IListIndexesResponse]>;
listIndexes(request: protosTypes.google.firestore.admin.v1.IListIndexesRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.admin.v1.IIndex[], protosTypes.google.firestore.admin.v1.IListIndexesRequest | null, protosTypes.google.firestore.admin.v1.IListIndexesResponse>): void;
/**
* Equivalent to {@link listIndexes}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listIndexes} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
* @param {string} request.filter
* The filter to apply to list results.
* @param {number} request.pageSize
* The number of results to return.
* @param {string} request.pageToken
* A page token, returned from a previous call to
* [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes], that may be used to get the next
* page of results.
* @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 an object representing [Index]{@link google.firestore.admin.v1.Index} on 'data' event.
*/
listIndexesStream(request?: protosTypes.google.firestore.admin.v1.IListIndexesRequest, options?: gax.CallOptions | {}): Transform;
listFields(request: protosTypes.google.firestore.admin.v1.IListFieldsRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.admin.v1.IField[], protosTypes.google.firestore.admin.v1.IListFieldsRequest | null, protosTypes.google.firestore.admin.v1.IListFieldsResponse]>;
listFields(request: protosTypes.google.firestore.admin.v1.IListFieldsRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.admin.v1.IField[], protosTypes.google.firestore.admin.v1.IListFieldsRequest | null, protosTypes.google.firestore.admin.v1.IListFieldsResponse>): void;
/**
* Equivalent to {@link listFields}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listFields} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
* @param {string} request.filter
* The filter to apply to list results. Currently,
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] only supports listing fields
* that have been explicitly overridden. To issue this query, call
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] with the filter set to
* `indexConfig.usesAncestorConfig:false`.
* @param {number} request.pageSize
* The number of results to return.
* @param {string} request.pageToken
* A page token, returned from a previous call to
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields], that may be used to get the next
* page of results.
* @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 an object representing [Field]{@link google.firestore.admin.v1.Field} on 'data' event.
*/
listFieldsStream(request?: protosTypes.google.firestore.admin.v1.IListFieldsRequest, options?: gax.CallOptions | {}): Transform;
/**
* Return a fully-qualified collectiongroup resource name string.
*
* @param {string} project
* @param {string} database
* @param {string} collection
* @returns {string} Resource name string.
*/
collectionGroupPath(project: string, database: string, collection: string): string;
/**
* Parse the project from CollectionGroup resource.
*
* @param {string} collectiongroupName
* A fully-qualified path representing CollectionGroup resource.
* @returns {string} A string representing the project.
*/
matchProjectFromCollectionGroupName(collectiongroupName: string): string;
/**
* Parse the database from CollectionGroup resource.
*
* @param {string} collectiongroupName
* A fully-qualified path representing CollectionGroup resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromCollectionGroupName(collectiongroupName: string): string;
/**
* Parse the collection from CollectionGroup resource.
*
* @param {string} collectiongroupName
* A fully-qualified path representing CollectionGroup resource.
* @returns {string} A string representing the collection.
*/
matchCollectionFromCollectionGroupName(collectiongroupName: string): string;
/**
* Return a fully-qualified index resource name string.
*
* @param {string} project
* @param {string} database
* @param {string} collection
* @param {string} index
* @returns {string} Resource name string.
*/
indexPath(project: string, database: string, collection: string, index: string): string;
/**
* Parse the project from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the project.
*/
matchProjectFromIndexName(indexName: string): string;
/**
* Parse the database from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromIndexName(indexName: string): string;
/**
* Parse the collection from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the collection.
*/
matchCollectionFromIndexName(indexName: string): string;
/**
* Parse the index from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the index.
*/
matchIndexFromIndexName(indexName: string): string;
/**
* Return a fully-qualified field resource name string.
*
* @param {string} project
* @param {string} database
* @param {string} collection
* @param {string} field
* @returns {string} Resource name string.
*/
fieldPath(project: string, database: string, collection: string, field: string): string;
/**
* Parse the project from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the project.
*/
matchProjectFromFieldName(fieldName: string): string;
/**
* Parse the database from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromFieldName(fieldName: string): string;
/**
* Parse the collection from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the collection.
*/
matchCollectionFromFieldName(fieldName: string): string;
/**
* Parse the field from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the field.
*/
matchFieldFromFieldName(fieldName: string): string;
/**
* Return a fully-qualified database resource name string.
*
* @param {string} project
* @param {string} database
* @returns {string} Resource name string.
*/
databasePath(project: string, database: string): string;
/**
* Parse the project from Database resource.
*
* @param {string} databaseName
* A fully-qualified path representing Database resource.
* @returns {string} A string representing the project.
*/
matchProjectFromDatabaseName(databaseName: string): string;
/**
* Parse the database from Database resource.
*
* @param {string} databaseName
* A fully-qualified path representing Database resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromDatabaseName(databaseName: string): string;
/**
* Terminate the GRPC channel and close the client.
*
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void>;
}

View File

@ -0,0 +1,907 @@
"use strict";
// Copyright 2019 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 });
const gax = require("google-gax");
const path = require("path");
const gapicConfig = require("./firestore_admin_client_config.json");
const version = require('../../../package.json').version;
/**
* Operations are created by service `FirestoreAdmin`, but are accessed via
* service `google.longrunning.Operations`.
* @class
* @memberof v1
*/
class FirestoreAdminClient {
/**
* Construct an instance of FirestoreAdminClient.
*
* @param {object} [options] - The configuration object. See the subsequent
* parameters for more details.
* @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://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
*/
constructor(opts) {
this._descriptors = { page: {}, stream: {}, longrunning: {} };
this._terminated = false;
// Ensure that options include the service address and port.
const staticMembers = this.constructor;
const servicePath = opts && opts.servicePath
? opts.servicePath
: opts && opts.apiEndpoint
? opts.apiEndpoint
: staticMembers.servicePath;
const port = opts && opts.port ? opts.port : staticMembers.port;
if (!opts) {
opts = { servicePath, port };
}
opts.servicePath = opts.servicePath || servicePath;
opts.port = opts.port || port;
opts.clientConfig = opts.clientConfig || {};
const isBrowser = typeof window !== 'undefined';
if (isBrowser) {
opts.fallback = true;
}
// If we are in browser, we are already using fallback because of the
// "browser" field in package.json.
// But if we were explicitly requested to use fallback, let's do it now.
const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax;
// Create a `gaxGrpc` object, with any grpc-specific options
// sent to the client.
opts.scopes = this.constructor.scopes;
const gaxGrpc = new gaxModule.GrpcClient(opts);
// Save the auth object to the client, for use by other methods.
this.auth = gaxGrpc.auth;
// Determine the client header string.
const clientHeader = [`gax/${gaxModule.version}`, `gapic/${version}`];
if (typeof process !== 'undefined' && 'versions' in process) {
clientHeader.push(`gl-node/${process.versions.node}`);
}
else {
clientHeader.push(`gl-web/${gaxModule.version}`);
}
if (!opts.fallback) {
clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`);
}
if (opts.libName && opts.libVersion) {
clientHeader.push(`${opts.libName}/${opts.libVersion}`);
}
// Load the applicable protos.
// For Node.js, pass the path to JSON proto file.
// For browsers, pass the JSON content.
const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json');
const protos = gaxGrpc.loadProto(opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath);
// This API contains "path templates"; forward-slash-separated
// identifiers to uniquely identify resources within the API.
// Create useful helper objects for these.
this._pathTemplates = {
collectionGroupPathTemplate: new gaxModule.PathTemplate('projects/{project}/databases/{database}/collectionGroups/{collection}'),
indexPathTemplate: new gaxModule.PathTemplate('projects/{project}/databases/{database}/collectionGroups/{collection}/indexes/{index}'),
fieldPathTemplate: new gaxModule.PathTemplate('projects/{project}/databases/{database}/collectionGroups/{collection}/fields/{field}'),
databasePathTemplate: new gaxModule.PathTemplate('projects/{project}/databases/{database}'),
};
// 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 = {
listIndexes: new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'indexes'),
listFields: new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'fields'),
};
// This API contains "long-running operations", which return a
// an Operation object that allows for tracking of the operation,
// rather than holding a request open.
const protoFilesRoot = opts.fallback
? gaxModule.protobuf.Root.fromJSON(require('../../protos/protos.json'))
: gaxModule.protobuf.loadSync(nodejsProtoPath);
this.operationsClient = gaxModule
.lro({
auth: this.auth,
grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined,
})
.operationsClient(opts);
const createIndexResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.Index');
const createIndexMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.IndexOperationMetadata');
const updateFieldResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.Field');
const updateFieldMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.FieldOperationMetadata');
const exportDocumentsResponse = protoFilesRoot.lookup('.google.firestore.admin.v1.ExportDocumentsResponse');
const exportDocumentsMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.ExportDocumentsMetadata');
const importDocumentsResponse = protoFilesRoot.lookup('.google.protobuf.Empty');
const importDocumentsMetadata = protoFilesRoot.lookup('.google.firestore.admin.v1.ImportDocumentsMetadata');
this._descriptors.longrunning = {
createIndex: new gaxModule.LongrunningDescriptor(this.operationsClient, createIndexResponse.decode.bind(createIndexResponse), createIndexMetadata.decode.bind(createIndexMetadata)),
updateField: new gaxModule.LongrunningDescriptor(this.operationsClient, updateFieldResponse.decode.bind(updateFieldResponse), updateFieldMetadata.decode.bind(updateFieldMetadata)),
exportDocuments: new gaxModule.LongrunningDescriptor(this.operationsClient, exportDocumentsResponse.decode.bind(exportDocumentsResponse), exportDocumentsMetadata.decode.bind(exportDocumentsMetadata)),
importDocuments: new gaxModule.LongrunningDescriptor(this.operationsClient, importDocumentsResponse.decode.bind(importDocumentsResponse), importDocumentsMetadata.decode.bind(importDocumentsMetadata)),
};
// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings('google.firestore.admin.v1.FirestoreAdmin', 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 = {};
// Put together the "service stub" for
// google.firestore.admin.v1.FirestoreAdmin.
this.firestoreAdminStub = gaxGrpc.createStub(opts.fallback
? protos.lookupService('google.firestore.admin.v1.FirestoreAdmin')
: // tslint:disable-next-line no-any
protos.google.firestore.admin.v1.FirestoreAdmin, opts);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const firestoreAdminStubMethods = [
'createIndex',
'listIndexes',
'getIndex',
'deleteIndex',
'getField',
'updateField',
'listFields',
'exportDocuments',
'importDocuments',
];
for (const methodName of firestoreAdminStubMethods) {
const innerCallPromise = this.firestoreAdminStub.then(stub => (...args) => {
if (this._terminated) {
return Promise.reject('The client has already been closed.');
}
return stub[methodName].apply(stub, args);
}, (err) => () => {
throw err;
});
const apiCall = gaxModule.createApiCall(innerCallPromise, defaults[methodName], this._descriptors.page[methodName] ||
this._descriptors.stream[methodName] ||
this._descriptors.longrunning[methodName]);
this._innerApiCalls[methodName] = (argument, callOptions, callback) => {
return apiCall(argument, callOptions, callback);
};
}
}
/**
* The DNS address for this API service.
*/
static get servicePath() {
return 'firestore.googleapis.com';
}
/**
* The DNS address for this API service - same as servicePath(),
* exists for compatibility reasons.
*/
static get apiEndpoint() {
return 'firestore.googleapis.com';
}
/**
* The port for this API service.
*/
static get port() {
return 443;
}
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
*/
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.
* @param {function(Error, string)} callback - the callback to
* be called with the current project Id.
*/
getProjectId(callback) {
if (callback) {
this.auth.getProjectId(callback);
return;
}
return this.auth.getProjectId();
}
/**
* Gets a composite index.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. A name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}`
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Index]{@link google.firestore.admin.v1.Index}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
getIndex(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'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.getIndex(request, options, callback);
}
/**
* Deletes a composite index.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. A name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}`
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
deleteIndex(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'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.deleteIndex(request, options, callback);
}
/**
* Gets the metadata and configuration for a Field.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. A name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}`
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Field]{@link google.firestore.admin.v1.Field}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
getField(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'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.getField(request, options, callback);
}
/**
* Creates a composite index. This returns a [google.longrunning.Operation][google.longrunning.Operation]
* which may be used to track the status of the creation. The metadata for
* the operation will be the type [IndexOperationMetadata][google.firestore.admin.v1.IndexOperationMetadata].
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
* @param {google.firestore.admin.v1.Index} request.index
* Required. The composite index to create.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
createIndex(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'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.createIndex(request, options, callback);
}
/**
* Updates a field configuration. Currently, field updates apply only to
* single field index configuration. However, calls to
* [FirestoreAdmin.UpdateField][google.firestore.admin.v1.FirestoreAdmin.UpdateField] should provide a field mask to avoid
* changing any configuration that the caller isn't aware of. The field mask
* should be specified as: `{ paths: "index_config" }`.
*
* This call returns a [google.longrunning.Operation][google.longrunning.Operation] which may be used to
* track the status of the field update. The metadata for
* the operation will be the type [FieldOperationMetadata][google.firestore.admin.v1.FieldOperationMetadata].
*
* To configure the default field settings for the database, use
* the special `Field` with resource name:
* `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`.
*
* @param {Object} request
* The request object that will be sent.
* @param {google.firestore.admin.v1.Field} request.field
* Required. The field to be updated.
* @param {google.protobuf.FieldMask} request.updateMask
* A mask, relative to the field. If specified, only configuration specified
* by this field_mask will be updated in the field.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
updateField(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'] = gax.routingHeader.fromParams({
field_name: request.field.name || '',
});
return this._innerApiCalls.updateField(request, options, callback);
}
/**
* Exports a copy of all or a subset of documents from Google Cloud Firestore
* to another storage system, such as Google Cloud Storage. Recent updates to
* documents may not be reflected in the export. The export occurs in the
* background and its progress can be monitored and managed via the
* Operation resource that is created. The output of an export may only be
* used once the associated operation is done. If an export operation is
* cancelled before completion it may leave partial data behind in Google
* Cloud Storage.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. Database to export. Should be of the form:
* `projects/{project_id}/databases/{database_id}`.
* @param {string[]} request.collectionIds
* Which collection ids to export. Unspecified means all collections.
* @param {string} request.outputUriPrefix
* The output URI. Currently only supports Google Cloud Storage URIs of the
* form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name
* of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional
* Google Cloud Storage namespace path. When
* choosing a name, be sure to consider Google Cloud Storage naming
* guidelines: https://cloud.google.com/storage/docs/naming.
* If the URI is a bucket (without a namespace path), a prefix will be
* generated based on the start time.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
exportDocuments(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'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.exportDocuments(request, options, callback);
}
/**
* Imports documents into Google Cloud Firestore. Existing documents with the
* same name are overwritten. The import occurs in the background and its
* progress can be monitored and managed via the Operation resource that is
* created. If an ImportDocuments operation is cancelled, it is possible
* that a subset of the data has already been imported to Cloud Firestore.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. Database to import into. Should be of the form:
* `projects/{project_id}/databases/{database_id}`.
* @param {string[]} request.collectionIds
* Which collection ids to import. Unspecified means all collections included
* in the import.
* @param {string} request.inputUriPrefix
* Location of the exported files.
* This must match the output_uri_prefix of an ExportDocumentsResponse from
* an export that has completed successfully.
* See:
* [google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix][google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix].
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
importDocuments(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'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.importDocuments(request, options, callback);
}
/**
* Lists composite indexes.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
* @param {string} request.filter
* The filter to apply to list results.
* @param {number} request.pageSize
* The number of results to return.
* @param {string} request.pageToken
* A page token, returned from a previous call to
* [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes], that may be used to get the next
* page of results.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [Index]{@link google.firestore.admin.v1.Index}.
* The client library support auto-pagination by default: it will call the API as many
* times as needed and will merge results from all the pages into this array.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of [Index]{@link google.firestore.admin.v1.Index} that corresponds to
* the one page received from the API server.
* If the second element is not null it contains the request object of type [ListIndexesRequest]{@link google.firestore.admin.v1.ListIndexesRequest}
* that can be used to obtain the next page of the results.
* If it is null, the next page does not exist.
* The third element contains the raw response received from the API server. Its type is
* [ListIndexesResponse]{@link google.firestore.admin.v1.ListIndexesResponse}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
listIndexes(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'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listIndexes(request, options, callback);
}
/**
* Equivalent to {@link listIndexes}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listIndexes} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
* @param {string} request.filter
* The filter to apply to list results.
* @param {number} request.pageSize
* The number of results to return.
* @param {string} request.pageToken
* A page token, returned from a previous call to
* [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes], that may be used to get the next
* page of results.
* @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 an object representing [Index]{@link google.firestore.admin.v1.Index} on 'data' event.
*/
listIndexesStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listIndexes.createStream(this._innerApiCalls.listIndexes, request, callSettings);
}
/**
* Lists the field configuration and metadata for this database.
*
* Currently, [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] only supports listing fields
* that have been explicitly overridden. To issue this query, call
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] with the filter set to
* `indexConfig.usesAncestorConfig:false`.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
* @param {string} request.filter
* The filter to apply to list results. Currently,
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] only supports listing fields
* that have been explicitly overridden. To issue this query, call
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] with the filter set to
* `indexConfig.usesAncestorConfig:false`.
* @param {number} request.pageSize
* The number of results to return.
* @param {string} request.pageToken
* A page token, returned from a previous call to
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields], that may be used to get the next
* page of results.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [Field]{@link google.firestore.admin.v1.Field}.
* The client library support auto-pagination by default: it will call the API as many
* times as needed and will merge results from all the pages into this array.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of [Field]{@link google.firestore.admin.v1.Field} that corresponds to
* the one page received from the API server.
* If the second element is not null it contains the request object of type [ListFieldsRequest]{@link google.firestore.admin.v1.ListFieldsRequest}
* that can be used to obtain the next page of the results.
* If it is null, the next page does not exist.
* The third element contains the raw response received from the API server. Its type is
* [ListFieldsResponse]{@link google.firestore.admin.v1.ListFieldsResponse}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
listFields(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'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listFields(request, options, callback);
}
/**
* Equivalent to {@link listFields}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listFields} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
* @param {string} request.filter
* The filter to apply to list results. Currently,
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] only supports listing fields
* that have been explicitly overridden. To issue this query, call
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] with the filter set to
* `indexConfig.usesAncestorConfig:false`.
* @param {number} request.pageSize
* The number of results to return.
* @param {string} request.pageToken
* A page token, returned from a previous call to
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields], that may be used to get the next
* page of results.
* @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 an object representing [Field]{@link google.firestore.admin.v1.Field} on 'data' event.
*/
listFieldsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listFields.createStream(this._innerApiCalls.listFields, request, callSettings);
}
// --------------------
// -- Path templates --
// --------------------
/**
* Return a fully-qualified collectiongroup resource name string.
*
* @param {string} project
* @param {string} database
* @param {string} collection
* @returns {string} Resource name string.
*/
collectionGroupPath(project, database, collection) {
return this._pathTemplates.collectiongroupPathTemplate.render({
project,
database,
collection,
});
}
/**
* Parse the project from CollectionGroup resource.
*
* @param {string} collectiongroupName
* A fully-qualified path representing CollectionGroup resource.
* @returns {string} A string representing the project.
*/
matchProjectFromCollectionGroupName(collectiongroupName) {
return this._pathTemplates.collectiongroupPathTemplate.match(collectiongroupName).project;
}
/**
* Parse the database from CollectionGroup resource.
*
* @param {string} collectiongroupName
* A fully-qualified path representing CollectionGroup resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromCollectionGroupName(collectiongroupName) {
return this._pathTemplates.collectiongroupPathTemplate.match(collectiongroupName).database;
}
/**
* Parse the collection from CollectionGroup resource.
*
* @param {string} collectiongroupName
* A fully-qualified path representing CollectionGroup resource.
* @returns {string} A string representing the collection.
*/
matchCollectionFromCollectionGroupName(collectiongroupName) {
return this._pathTemplates.collectiongroupPathTemplate.match(collectiongroupName).collection;
}
/**
* Return a fully-qualified index resource name string.
*
* @param {string} project
* @param {string} database
* @param {string} collection
* @param {string} index
* @returns {string} Resource name string.
*/
indexPath(project, database, collection, index) {
return this._pathTemplates.indexPathTemplate.render({
project,
database,
collection,
index,
});
}
/**
* Parse the project from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the project.
*/
matchProjectFromIndexName(indexName) {
return this._pathTemplates.indexPathTemplate.match(indexName).project;
}
/**
* Parse the database from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromIndexName(indexName) {
return this._pathTemplates.indexPathTemplate.match(indexName).database;
}
/**
* Parse the collection from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the collection.
*/
matchCollectionFromIndexName(indexName) {
return this._pathTemplates.indexPathTemplate.match(indexName).collection;
}
/**
* Parse the index from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the index.
*/
matchIndexFromIndexName(indexName) {
return this._pathTemplates.indexPathTemplate.match(indexName).index;
}
/**
* Return a fully-qualified field resource name string.
*
* @param {string} project
* @param {string} database
* @param {string} collection
* @param {string} field
* @returns {string} Resource name string.
*/
fieldPath(project, database, collection, field) {
return this._pathTemplates.fieldPathTemplate.render({
project,
database,
collection,
field,
});
}
/**
* Parse the project from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the project.
*/
matchProjectFromFieldName(fieldName) {
return this._pathTemplates.fieldPathTemplate.match(fieldName).project;
}
/**
* Parse the database from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromFieldName(fieldName) {
return this._pathTemplates.fieldPathTemplate.match(fieldName).database;
}
/**
* Parse the collection from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the collection.
*/
matchCollectionFromFieldName(fieldName) {
return this._pathTemplates.fieldPathTemplate.match(fieldName).collection;
}
/**
* Parse the field from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the field.
*/
matchFieldFromFieldName(fieldName) {
return this._pathTemplates.fieldPathTemplate.match(fieldName).field;
}
/**
* Return a fully-qualified database resource name string.
*
* @param {string} project
* @param {string} database
* @returns {string} Resource name string.
*/
databasePath(project, database) {
return this._pathTemplates.databasePathTemplate.render({
project,
database,
});
}
/**
* Parse the project from Database resource.
*
* @param {string} databaseName
* A fully-qualified path representing Database resource.
* @returns {string} A string representing the project.
*/
matchProjectFromDatabaseName(databaseName) {
return this._pathTemplates.databasePathTemplate.match(databaseName).project;
}
/**
* Parse the database from Database resource.
*
* @param {string} databaseName
* A fully-qualified path representing Database resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromDatabaseName(databaseName) {
return this._pathTemplates.databasePathTemplate.match(databaseName)
.database;
}
/**
* Terminate the GRPC channel and close the client.
*
* The client will no longer be usable and all future behavior is undefined.
*/
close() {
if (!this._terminated) {
return this.firestoreAdminStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
}
}
exports.FirestoreAdminClient = FirestoreAdminClient;
//# sourceMappingURL=firestore_admin_client.js.map

View File

@ -0,0 +1,76 @@
{
"interfaces": {
"google.firestore.admin.v1.FirestoreAdmin": {
"retry_codes": {
"non_idempotent": [],
"idempotent": [
"DEADLINE_EXCEEDED",
"UNAVAILABLE"
],
"deadline_exceeded_internal_unavailable": [
"DEADLINE_EXCEEDED",
"INTERNAL",
"UNAVAILABLE"
]
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 60000,
"rpc_timeout_multiplier": 1,
"max_rpc_timeout_millis": 60000,
"total_timeout_millis": 600000
}
},
"methods": {
"CreateIndex": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"ListIndexes": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"GetIndex": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"DeleteIndex": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"GetField": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"UpdateField": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"ListFields": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"ExportDocuments": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"ImportDocuments": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
}
}
}
}
}

View File

@ -0,0 +1,7 @@
[
"../../protos/google/firestore/admin/v1/index.proto",
"../../protos/google/firestore/admin/v1/field.proto",
"../../protos/google/firestore/admin/v1/firestore_admin.proto",
"../../protos/google/firestore/admin/v1/location.proto",
"../../protos/google/firestore/admin/v1/operation.proto"
]

View File

@ -0,0 +1,273 @@
/// <reference types="node" />
import * as gax from 'google-gax';
import { Callback, ClientOptions } from 'google-gax';
import { Transform } from 'stream';
import * as protosTypes from '../../protos/firestore_v1_proto_api';
/**
* 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 (GCP) accelerate
* building truly serverless apps.
* @class
* @memberof v1
*/
export declare class FirestoreClient {
private _descriptors;
private _innerApiCalls;
private _terminated;
auth: gax.GoogleAuth;
firestoreStub: Promise<{
[name: string]: Function;
}>;
/**
* Construct an instance of FirestoreClient.
*
* @param {object} [options] - The configuration object. See the subsequent
* parameters for more details.
* @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://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
*/
constructor(opts?: ClientOptions);
/**
* The DNS address for this API service.
*/
static readonly servicePath: string;
/**
* The DNS address for this API service - same as servicePath(),
* exists for compatibility reasons.
*/
static readonly apiEndpoint: string;
/**
* The port for this API service.
*/
static readonly port: number;
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
*/
static readonly scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback: Callback<string, undefined, undefined>): void;
getDocument(request: protosTypes.google.firestore.v1.IGetDocumentRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1.IDocument, protosTypes.google.firestore.v1.IGetDocumentRequest | undefined, {} | undefined]>;
getDocument(request: protosTypes.google.firestore.v1.IGetDocumentRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1.IDocument, protosTypes.google.firestore.v1.IGetDocumentRequest | undefined, {} | undefined>): void;
createDocument(request: protosTypes.google.firestore.v1.ICreateDocumentRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1.IDocument, protosTypes.google.firestore.v1.ICreateDocumentRequest | undefined, {} | undefined]>;
createDocument(request: protosTypes.google.firestore.v1.ICreateDocumentRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1.IDocument, protosTypes.google.firestore.v1.ICreateDocumentRequest | undefined, {} | undefined>): void;
updateDocument(request: protosTypes.google.firestore.v1.IUpdateDocumentRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1.IDocument, protosTypes.google.firestore.v1.IUpdateDocumentRequest | undefined, {} | undefined]>;
updateDocument(request: protosTypes.google.firestore.v1.IUpdateDocumentRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1.IDocument, protosTypes.google.firestore.v1.IUpdateDocumentRequest | undefined, {} | undefined>): void;
deleteDocument(request: protosTypes.google.firestore.v1.IDeleteDocumentRequest, options?: gax.CallOptions): Promise<[protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.v1.IDeleteDocumentRequest | undefined, {} | undefined]>;
deleteDocument(request: protosTypes.google.firestore.v1.IDeleteDocumentRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.v1.IDeleteDocumentRequest | undefined, {} | undefined>): void;
beginTransaction(request: protosTypes.google.firestore.v1.IBeginTransactionRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1.IBeginTransactionResponse, protosTypes.google.firestore.v1.IBeginTransactionRequest | undefined, {} | undefined]>;
beginTransaction(request: protosTypes.google.firestore.v1.IBeginTransactionRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1.IBeginTransactionResponse, protosTypes.google.firestore.v1.IBeginTransactionRequest | undefined, {} | undefined>): void;
commit(request: protosTypes.google.firestore.v1.ICommitRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1.ICommitResponse, protosTypes.google.firestore.v1.ICommitRequest | undefined, {} | undefined]>;
commit(request: protosTypes.google.firestore.v1.ICommitRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1.ICommitResponse, protosTypes.google.firestore.v1.ICommitRequest | undefined, {} | undefined>): void;
rollback(request: protosTypes.google.firestore.v1.IRollbackRequest, options?: gax.CallOptions): Promise<[protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.v1.IRollbackRequest | undefined, {} | undefined]>;
rollback(request: protosTypes.google.firestore.v1.IRollbackRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.v1.IRollbackRequest | undefined, {} | undefined>): void;
/**
* 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 may not be older than 60 seconds.
* @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 [BatchGetDocumentsResponse]{@link google.firestore.v1.BatchGetDocumentsResponse} on 'data' event.
*/
batchGetDocuments(request?: protosTypes.google.firestore.v1.IBatchGetDocumentsRequest, options?: gax.CallOptions): gax.CancellableStream;
/**
* 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
* 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 may not be older than 60 seconds.
* @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 [RunQueryResponse]{@link google.firestore.v1.RunQueryResponse} on 'data' event.
*/
runQuery(request?: protosTypes.google.firestore.v1.IRunQueryRequest, options?: gax.CallOptions): gax.CancellableStream;
/**
* Streams batches of document updates and deletes, in order.
*
* @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 [WriteRequest]{@link google.firestore.v1.WriteRequest} for write() method, and
* will emit objects representing [WriteResponse]{@link google.firestore.v1.WriteResponse} on 'data' event asynchronously.
*/
write(options?: gax.CallOptions): gax.CancellableStream;
/**
* Listens to changes.
*
* @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 [ListenRequest]{@link google.firestore.v1.ListenRequest} for write() method, and
* will emit objects representing [ListenResponse]{@link google.firestore.v1.ListenResponse} on 'data' event asynchronously.
*/
listen(options?: gax.CallOptions): gax.CancellableStream;
listDocuments(request: protosTypes.google.firestore.v1.IListDocumentsRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1.IDocument[], protosTypes.google.firestore.v1.IListDocumentsRequest | null, protosTypes.google.firestore.v1.IListDocumentsResponse]>;
listDocuments(request: protosTypes.google.firestore.v1.IListDocumentsRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1.IDocument[], protosTypes.google.firestore.v1.IListDocumentsRequest | null, protosTypes.google.firestore.v1.IListDocumentsResponse>): void;
/**
* Equivalent to {@link listDocuments}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listDocuments} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @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
* Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`
* or `messages`.
* @param {number} request.pageSize
* The maximum number of documents to return.
* @param {string} request.pageToken
* The `next_page_token` value returned from a previous List request, if any.
* @param {string} request.orderBy
* The order to sort results by. For example: `priority desc, name`.
* @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.protobuf.Timestamp} request.readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
* @param {boolean} request.showMissing
* If the list should show missing documents. A missing document is a
* document that does not exist but has sub-documents. These documents will
* be returned with a key but will not have fields, [Document.create_time][google.firestore.v1.Document.create_time],
* or [Document.update_time][google.firestore.v1.Document.update_time] set.
*
* Requests with `show_missing` may not specify `where` or
* `order_by`.
* @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 an object representing [Document]{@link google.firestore.v1.Document} on 'data' event.
*/
listDocumentsStream(request?: protosTypes.google.firestore.v1.IListDocumentsRequest, options?: gax.CallOptions | {}): Transform;
listCollectionIds(request: protosTypes.google.firestore.v1.IListCollectionIdsRequest, options?: gax.CallOptions): Promise<[string[], protosTypes.google.firestore.v1.IListCollectionIdsRequest | null, protosTypes.google.firestore.v1.IListCollectionIdsResponse]>;
listCollectionIds(request: protosTypes.google.firestore.v1.IListCollectionIdsRequest, options: gax.CallOptions, callback: Callback<string[], protosTypes.google.firestore.v1.IListCollectionIdsRequest | null, protosTypes.google.firestore.v1.IListCollectionIdsResponse>): void;
/**
* Equivalent to {@link listCollectionIds}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listCollectionIds} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent document. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
* @param {number} request.pageSize
* The maximum number of results to return.
* @param {string} request.pageToken
* A page token. Must be a value from
* [ListCollectionIdsResponse][google.firestore.v1.ListCollectionIdsResponse].
* @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 an object representing string on 'data' event.
*/
listCollectionIdsStream(request?: protosTypes.google.firestore.v1.IListCollectionIdsRequest, options?: gax.CallOptions | {}): Transform;
/**
* Terminate the GRPC channel and close the client.
*
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void>;
}

View File

@ -0,0 +1,833 @@
"use strict";
// Copyright 2019 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 });
const gax = require("google-gax");
const path = require("path");
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 (GCP) accelerate
* building truly serverless apps.
* @class
* @memberof v1
*/
class FirestoreClient {
/**
* Construct an instance of FirestoreClient.
*
* @param {object} [options] - The configuration object. See the subsequent
* parameters for more details.
* @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://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
*/
constructor(opts) {
this._descriptors = { page: {}, stream: {}, longrunning: {} };
this._terminated = false;
// Ensure that options include the service address and port.
const staticMembers = this.constructor;
const servicePath = opts && opts.servicePath
? opts.servicePath
: opts && opts.apiEndpoint
? opts.apiEndpoint
: staticMembers.servicePath;
const port = opts && opts.port ? opts.port : staticMembers.port;
if (!opts) {
opts = { servicePath, port };
}
opts.servicePath = opts.servicePath || servicePath;
opts.port = opts.port || port;
opts.clientConfig = opts.clientConfig || {};
const isBrowser = typeof window !== 'undefined';
if (isBrowser) {
opts.fallback = true;
}
// If we are in browser, we are already using fallback because of the
// "browser" field in package.json.
// But if we were explicitly requested to use fallback, let's do it now.
const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax;
// Create a `gaxGrpc` object, with any grpc-specific options
// sent to the client.
opts.scopes = this.constructor.scopes;
const gaxGrpc = new gaxModule.GrpcClient(opts);
// Save the auth object to the client, for use by other methods.
this.auth = gaxGrpc.auth;
// Determine the client header string.
const clientHeader = [`gax/${gaxModule.version}`, `gapic/${version}`];
if (typeof process !== 'undefined' && 'versions' in process) {
clientHeader.push(`gl-node/${process.versions.node}`);
}
else {
clientHeader.push(`gl-web/${gaxModule.version}`);
}
if (!opts.fallback) {
clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`);
}
if (opts.libName && opts.libVersion) {
clientHeader.push(`${opts.libName}/${opts.libVersion}`);
}
// Load the applicable protos.
// For Node.js, pass the path to JSON proto file.
// For browsers, pass the JSON content.
const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json');
const protos = gaxGrpc.loadProto(opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath);
// 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 gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'),
listCollectionIds: new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'collectionIds'),
};
// Some of the methods on this service provide streaming responses.
// Provide descriptors for these.
this._descriptors.stream = {
batchGetDocuments: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING),
runQuery: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING),
write: new gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING),
listen: new gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING),
};
// Put together the default options sent with requests.
const defaults = 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 = {};
// Put together the "service stub" for
// google.firestore.v1.Firestore.
this.firestoreStub = gaxGrpc.createStub(opts.fallback
? protos.lookupService('google.firestore.v1.Firestore')
: // tslint:disable-next-line no-any
protos.google.firestore.v1.Firestore, opts);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const firestoreStubMethods = [
'getDocument',
'listDocuments',
'createDocument',
'updateDocument',
'deleteDocument',
'batchGetDocuments',
'beginTransaction',
'commit',
'rollback',
'runQuery',
'write',
'listen',
'listCollectionIds',
];
for (const methodName of firestoreStubMethods) {
const innerCallPromise = this.firestoreStub.then(stub => (...args) => {
if (this._terminated) {
return Promise.reject('The client has already been closed.');
}
return stub[methodName].apply(stub, args);
}, (err) => () => {
throw err;
});
const apiCall = gaxModule.createApiCall(innerCallPromise, defaults[methodName], this._descriptors.page[methodName] ||
this._descriptors.stream[methodName] ||
this._descriptors.longrunning[methodName]);
this._innerApiCalls[methodName] = (argument, callOptions, callback) => {
return apiCall(argument, callOptions, callback);
};
}
}
/**
* The DNS address for this API service.
*/
static get servicePath() {
return 'firestore.googleapis.com';
}
/**
* The DNS address for this API service - same as servicePath(),
* exists for compatibility reasons.
*/
static get apiEndpoint() {
return 'firestore.googleapis.com';
}
/**
* The port for this API service.
*/
static get port() {
return 443;
}
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
*/
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.
* @param {function(Error, string)} callback - the callback to
* be called with the current project Id.
*/
getProjectId(callback) {
if (callback) {
this.auth.getProjectId(callback);
return;
}
return this.auth.getProjectId();
}
/**
* Gets a single document.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. The resource name of the Document to get. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* @param {google.firestore.v1.DocumentMask} request.mask
* The fields to return. If not set, returns all fields.
*
* If the 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 the document in a transaction.
* @param {google.protobuf.Timestamp} request.readTime
* Reads the version of the document at the given time.
* This may not be older than 60 seconds.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Document]{@link google.firestore.v1.Document}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.getDocument(request, options, callback);
}
/**
* Creates a new document.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent resource. For example:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}`
* @param {string} request.collectionId
* Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`.
* @param {string} request.documentId
* The client-assigned document ID to use for this document.
*
* Optional. If not specified, an ID will be assigned by the service.
* @param {google.firestore.v1.Document} request.document
* Required. The document to create. `name` must not be set.
* @param {google.firestore.v1.DocumentMask} request.mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Document]{@link google.firestore.v1.Document}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.createDocument(request, options, callback);
}
/**
* Updates or inserts a document.
*
* @param {Object} request
* The request object that will be sent.
* @param {google.firestore.v1.Document} request.document
* Required. The updated document.
* Creates the document if it does not already exist.
* @param {google.firestore.v1.DocumentMask} request.updateMask
* The fields to update.
* None of the field paths in the mask may contain a reserved name.
*
* If the document exists on the server and has fields not referenced in the
* mask, they are left unchanged.
* Fields referenced in the mask, but not present in the input document, are
* deleted from the document on the server.
* @param {google.firestore.v1.DocumentMask} request.mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
* @param {google.firestore.v1.Precondition} request.currentDocument
* An optional precondition on the document.
* The request will fail if this is set and not met by the target document.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Document]{@link google.firestore.v1.Document}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
'document.name': request.document.name || '',
});
return this._innerApiCalls.updateDocument(request, options, callback);
}
/**
* Deletes a document.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. The resource name of the Document to delete. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* @param {google.firestore.v1.Precondition} request.currentDocument
* An optional precondition on the document.
* The request will fail if this is set and not met by the target document.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.deleteDocument(request, options, callback);
}
/**
* Starts a new transaction.
*
* @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 {google.firestore.v1.TransactionOptions} request.options
* The options for the transaction.
* Defaults to a read-write transaction.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [BeginTransactionResponse]{@link google.firestore.v1.BeginTransactionResponse}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.beginTransaction(request, options, callback);
}
/**
* Commits a transaction, while optionally updating documents.
*
* @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 {number[]} request.writes
* The writes to apply.
*
* Always executed atomically and in order.
* @param {Buffer} request.transaction
* If set, applies all writes in this transaction, and commits it.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [CommitResponse]{@link google.firestore.v1.CommitResponse}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.commit(request, options, callback);
}
/**
* Rolls back a transaction.
*
* @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 {Buffer} request.transaction
* Required. The transaction to roll back.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.rollback(request, options, callback);
}
/**
* 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 may not be older than 60 seconds.
* @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 [BatchGetDocumentsResponse]{@link google.firestore.v1.BatchGetDocumentsResponse} on 'data' event.
*/
batchGetDocuments(request, options) {
request = request || {};
options = 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
* 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 may not be older than 60 seconds.
* @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 [RunQueryResponse]{@link google.firestore.v1.RunQueryResponse} on 'data' event.
*/
runQuery(request, options) {
request = request || {};
options = options || {};
return this._innerApiCalls.runQuery(request, options);
}
/**
* Streams batches of document updates and deletes, in order.
*
* @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 [WriteRequest]{@link google.firestore.v1.WriteRequest} for write() method, and
* will emit objects representing [WriteResponse]{@link google.firestore.v1.WriteResponse} on 'data' event asynchronously.
*/
write(options) {
options = options || {};
return this._innerApiCalls.write(options);
}
/**
* Listens to changes.
*
* @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 [ListenRequest]{@link google.firestore.v1.ListenRequest} for write() method, and
* will emit objects representing [ListenResponse]{@link google.firestore.v1.ListenResponse} on 'data' event asynchronously.
*/
listen(options) {
options = options || {};
return this._innerApiCalls.listen({}, options);
}
/**
* Lists documents.
*
* @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
* Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`
* or `messages`.
* @param {number} request.pageSize
* The maximum number of documents to return.
* @param {string} request.pageToken
* The `next_page_token` value returned from a previous List request, if any.
* @param {string} request.orderBy
* The order to sort results by. For example: `priority desc, name`.
* @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.protobuf.Timestamp} request.readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
* @param {boolean} request.showMissing
* If the list should show missing documents. A missing document is a
* document that does not exist but has sub-documents. These documents will
* be returned with a key but will not have fields, [Document.create_time][google.firestore.v1.Document.create_time],
* or [Document.update_time][google.firestore.v1.Document.update_time] set.
*
* Requests with `show_missing` may not specify `where` or
* `order_by`.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [Document]{@link google.firestore.v1.Document}.
* The client library support auto-pagination by default: it will call the API as many
* times as needed and will merge results from all the pages into this array.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of [Document]{@link google.firestore.v1.Document} that corresponds to
* the one page received from the API server.
* If the second element is not null it contains the request object of type [ListDocumentsRequest]{@link google.firestore.v1.ListDocumentsRequest}
* that can be used to obtain the next page of the results.
* If it is null, the next page does not exist.
* The third element contains the raw response received from the API server. Its type is
* [ListDocumentsResponse]{@link google.firestore.v1.ListDocumentsResponse}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listDocuments(request, options, callback);
}
/**
* Equivalent to {@link listDocuments}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listDocuments} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @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
* Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`
* or `messages`.
* @param {number} request.pageSize
* The maximum number of documents to return.
* @param {string} request.pageToken
* The `next_page_token` value returned from a previous List request, if any.
* @param {string} request.orderBy
* The order to sort results by. For example: `priority desc, name`.
* @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.protobuf.Timestamp} request.readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
* @param {boolean} request.showMissing
* If the list should show missing documents. A missing document is a
* document that does not exist but has sub-documents. These documents will
* be returned with a key but will not have fields, [Document.create_time][google.firestore.v1.Document.create_time],
* or [Document.update_time][google.firestore.v1.Document.update_time] set.
*
* Requests with `show_missing` may not specify `where` or
* `order_by`.
* @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 an object representing [Document]{@link google.firestore.v1.Document} on 'data' event.
*/
listDocumentsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listDocuments.createStream(this._innerApiCalls.listDocuments, request, callSettings);
}
/**
* Lists all the collection IDs underneath a document.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent document. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
* @param {number} request.pageSize
* The maximum number of results to return.
* @param {string} request.pageToken
* A page token. Must be a value from
* [ListCollectionIdsResponse][google.firestore.v1.ListCollectionIdsResponse].
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of string.
* The client library support auto-pagination by default: it will call the API as many
* times as needed and will merge results from all the pages into this array.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of string that corresponds to
* the one page received from the API server.
* If the second element is not null it contains the request object of type [ListCollectionIdsRequest]{@link google.firestore.v1.ListCollectionIdsRequest}
* that can be used to obtain the next page of the results.
* If it is null, the next page does not exist.
* The third element contains the raw response received from the API server. Its type is
* [ListCollectionIdsResponse]{@link google.firestore.v1.ListCollectionIdsResponse}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
listCollectionIds(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'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listCollectionIds(request, options, callback);
}
/**
* Equivalent to {@link listCollectionIds}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listCollectionIds} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent document. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
* @param {number} request.pageSize
* The maximum number of results to return.
* @param {string} request.pageToken
* A page token. Must be a value from
* [ListCollectionIdsResponse][google.firestore.v1.ListCollectionIdsResponse].
* @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 an object representing string on 'data' event.
*/
listCollectionIdsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listCollectionIds.createStream(this._innerApiCalls.listCollectionIds, request, callSettings);
}
/**
* Terminate the GRPC channel and close the client.
*
* The client will no longer be usable and all future behavior is undefined.
*/
close() {
if (!this._terminated) {
return this.firestoreStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
}
}
exports.FirestoreClient = FirestoreClient;
//# sourceMappingURL=firestore_client.js.map

View File

@ -0,0 +1,96 @@
{
"interfaces": {
"google.firestore.v1.Firestore": {
"retry_codes": {
"non_idempotent": [],
"idempotent": [
"DEADLINE_EXCEEDED",
"UNAVAILABLE"
],
"deadline_exceeded_internal_unavailable": [
"DEADLINE_EXCEEDED",
"INTERNAL",
"UNAVAILABLE"
]
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 60000,
"rpc_timeout_multiplier": 1,
"max_rpc_timeout_millis": 60000,
"total_timeout_millis": 600000
}
},
"methods": {
"GetDocument": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"ListDocuments": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"CreateDocument": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"UpdateDocument": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"DeleteDocument": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"BatchGetDocuments": {
"timeout_millis": 300000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"BeginTransaction": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"Commit": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"Rollback": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"RunQuery": {
"timeout_millis": 300000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"Write": {
"timeout_millis": 86400000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"Listen": {
"timeout_millis": 86400000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
},
"ListCollectionIds": {
"timeout_millis": 60000,
"retry_codes_name": "deadline_exceeded_internal_unavailable",
"retry_params_name": "default"
}
}
}
}
}

View File

@ -0,0 +1,7 @@
[
"../../protos/google/firestore/v1/common.proto",
"../../protos/google/firestore/v1/document.proto",
"../../protos/google/firestore/v1/write.proto",
"../../protos/google/firestore/v1/query.proto",
"../../protos/google/firestore/v1/firestore.proto"
]

View File

@ -0,0 +1,3 @@
import { FirestoreAdminClient } from './firestore_admin_client';
import { FirestoreClient } from './firestore_client';
export { FirestoreClient, FirestoreAdminClient };

View File

@ -0,0 +1,24 @@
"use strict";
// Copyright 2019 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.
Object.defineProperty(exports, "__esModule", { value: true });
const firestore_admin_client_1 = require("./firestore_admin_client");
exports.FirestoreAdminClient = firestore_admin_client_1.FirestoreAdminClient;
const firestore_client_1 = require("./firestore_client");
exports.FirestoreClient = firestore_client_1.FirestoreClient;
// Doing something really horrible for reverse compatibility with original JavaScript exports
const existingExports = module.exports;
module.exports = firestore_client_1.FirestoreClient;
module.exports = Object.assign(module.exports, existingExports);
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1,281 @@
/// <reference types="node" />
import * as gax from 'google-gax';
import { Callback, ClientOptions } from 'google-gax';
import { Transform } from 'stream';
import * as protosTypes from '../../protos/firestore_v1beta1_proto_api';
/**
* The Cloud Firestore service.
*
* This service exposes several types of comparable timestamps:
*
* * `create_time` - The time at which a document was created. Changes only
* when a document is deleted, then re-created. Increases in a strict
* monotonic fashion.
* * `update_time` - The time at which a document was last updated. Changes
* every time a document is modified. Does not change when a write results
* in no modifications. Increases in a strict monotonic fashion.
* * `read_time` - The time at which a particular state was observed. Used
* to denote a consistent snapshot of the database or the time at which a
* Document was observed to not exist.
* * `commit_time` - The time at which the writes in a transaction were
* committed. Any read with an equal or greater `read_time` is guaranteed
* to see the effects of the transaction.
* @class
* @memberof v1beta1
*/
export declare class FirestoreClient {
private _descriptors;
private _innerApiCalls;
private _terminated;
auth: gax.GoogleAuth;
firestoreStub: Promise<{
[name: string]: Function;
}>;
/**
* Construct an instance of FirestoreClient.
*
* @param {object} [options] - The configuration object. See the subsequent
* parameters for more details.
* @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://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
*/
constructor(opts?: ClientOptions);
/**
* The DNS address for this API service.
*/
static readonly servicePath: string;
/**
* The DNS address for this API service - same as servicePath(),
* exists for compatibility reasons.
*/
static readonly apiEndpoint: string;
/**
* The port for this API service.
*/
static readonly port: number;
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
*/
static readonly scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback: Callback<string, undefined, undefined>): void;
getDocument(request: protosTypes.google.firestore.v1beta1.IGetDocumentRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1beta1.IDocument, protosTypes.google.firestore.v1beta1.IGetDocumentRequest | undefined, {} | undefined]>;
getDocument(request: protosTypes.google.firestore.v1beta1.IGetDocumentRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1beta1.IDocument, protosTypes.google.firestore.v1beta1.IGetDocumentRequest | undefined, {} | undefined>): void;
createDocument(request: protosTypes.google.firestore.v1beta1.ICreateDocumentRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1beta1.IDocument, protosTypes.google.firestore.v1beta1.ICreateDocumentRequest | undefined, {} | undefined]>;
createDocument(request: protosTypes.google.firestore.v1beta1.ICreateDocumentRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1beta1.IDocument, protosTypes.google.firestore.v1beta1.ICreateDocumentRequest | undefined, {} | undefined>): void;
updateDocument(request: protosTypes.google.firestore.v1beta1.IUpdateDocumentRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1beta1.IDocument, protosTypes.google.firestore.v1beta1.IUpdateDocumentRequest | undefined, {} | undefined]>;
updateDocument(request: protosTypes.google.firestore.v1beta1.IUpdateDocumentRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1beta1.IDocument, protosTypes.google.firestore.v1beta1.IUpdateDocumentRequest | undefined, {} | undefined>): void;
deleteDocument(request: protosTypes.google.firestore.v1beta1.IDeleteDocumentRequest, options?: gax.CallOptions): Promise<[protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.v1beta1.IDeleteDocumentRequest | undefined, {} | undefined]>;
deleteDocument(request: protosTypes.google.firestore.v1beta1.IDeleteDocumentRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.v1beta1.IDeleteDocumentRequest | undefined, {} | undefined>): void;
beginTransaction(request: protosTypes.google.firestore.v1beta1.IBeginTransactionRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1beta1.IBeginTransactionResponse, protosTypes.google.firestore.v1beta1.IBeginTransactionRequest | undefined, {} | undefined]>;
beginTransaction(request: protosTypes.google.firestore.v1beta1.IBeginTransactionRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1beta1.IBeginTransactionResponse, protosTypes.google.firestore.v1beta1.IBeginTransactionRequest | undefined, {} | undefined>): void;
commit(request: protosTypes.google.firestore.v1beta1.ICommitRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1beta1.ICommitResponse, protosTypes.google.firestore.v1beta1.ICommitRequest | undefined, {} | undefined]>;
commit(request: protosTypes.google.firestore.v1beta1.ICommitRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1beta1.ICommitResponse, protosTypes.google.firestore.v1beta1.ICommitRequest | undefined, {} | undefined>): void;
rollback(request: protosTypes.google.firestore.v1beta1.IRollbackRequest, options?: gax.CallOptions): Promise<[protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.v1beta1.IRollbackRequest | undefined, {} | undefined]>;
rollback(request: protosTypes.google.firestore.v1beta1.IRollbackRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.v1beta1.IRollbackRequest | undefined, {} | undefined>): void;
/**
* 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.v1beta1.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.v1beta1.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 may not be older than 60 seconds.
* @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 [BatchGetDocumentsResponse]{@link google.firestore.v1beta1.BatchGetDocumentsResponse} on 'data' event.
*/
batchGetDocuments(request?: protosTypes.google.firestore.v1beta1.IBatchGetDocumentsRequest, options?: gax.CallOptions): gax.CancellableStream;
/**
* 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.v1beta1.StructuredQuery} request.structuredQuery
* A structured query.
* @param {Buffer} request.transaction
* Reads documents in a transaction.
* @param {google.firestore.v1beta1.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 may not be older than 60 seconds.
* @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 [RunQueryResponse]{@link google.firestore.v1beta1.RunQueryResponse} on 'data' event.
*/
runQuery(request?: protosTypes.google.firestore.v1beta1.IRunQueryRequest, options?: gax.CallOptions): gax.CancellableStream;
/**
* Streams batches of document updates and deletes, in order.
*
* @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 [WriteRequest]{@link google.firestore.v1beta1.WriteRequest} for write() method, and
* will emit objects representing [WriteResponse]{@link google.firestore.v1beta1.WriteResponse} on 'data' event asynchronously.
*/
write(options?: gax.CallOptions): gax.CancellableStream;
/**
* Listens to changes.
*
* @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 [ListenRequest]{@link google.firestore.v1beta1.ListenRequest} for write() method, and
* will emit objects representing [ListenResponse]{@link google.firestore.v1beta1.ListenResponse} on 'data' event asynchronously.
*/
listen(options?: gax.CallOptions): gax.CancellableStream;
listDocuments(request: protosTypes.google.firestore.v1beta1.IListDocumentsRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.v1beta1.IDocument[], protosTypes.google.firestore.v1beta1.IListDocumentsRequest | null, protosTypes.google.firestore.v1beta1.IListDocumentsResponse]>;
listDocuments(request: protosTypes.google.firestore.v1beta1.IListDocumentsRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.v1beta1.IDocument[], protosTypes.google.firestore.v1beta1.IListDocumentsRequest | null, protosTypes.google.firestore.v1beta1.IListDocumentsResponse>): void;
/**
* Equivalent to {@link listDocuments}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listDocuments} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @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
* Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`
* or `messages`.
* @param {number} request.pageSize
* The maximum number of documents to return.
* @param {string} request.pageToken
* The `next_page_token` value returned from a previous List request, if any.
* @param {string} request.orderBy
* The order to sort results by. For example: `priority desc, name`.
* @param {google.firestore.v1beta1.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.protobuf.Timestamp} request.readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
* @param {boolean} request.showMissing
* If the list should show missing documents. A missing document is a
* document that does not exist but has sub-documents. These documents will
* be returned with a key but will not have fields, [Document.create_time][google.firestore.v1beta1.Document.create_time],
* or [Document.update_time][google.firestore.v1beta1.Document.update_time] set.
*
* Requests with `show_missing` may not specify `where` or
* `order_by`.
* @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 an object representing [Document]{@link google.firestore.v1beta1.Document} on 'data' event.
*/
listDocumentsStream(request?: protosTypes.google.firestore.v1beta1.IListDocumentsRequest, options?: gax.CallOptions | {}): Transform;
listCollectionIds(request: protosTypes.google.firestore.v1beta1.IListCollectionIdsRequest, options?: gax.CallOptions): Promise<[string[], protosTypes.google.firestore.v1beta1.IListCollectionIdsRequest | null, protosTypes.google.firestore.v1beta1.IListCollectionIdsResponse]>;
listCollectionIds(request: protosTypes.google.firestore.v1beta1.IListCollectionIdsRequest, options: gax.CallOptions, callback: Callback<string[], protosTypes.google.firestore.v1beta1.IListCollectionIdsRequest | null, protosTypes.google.firestore.v1beta1.IListCollectionIdsResponse>): void;
/**
* Equivalent to {@link listCollectionIds}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listCollectionIds} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent document. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
* @param {number} request.pageSize
* The maximum number of results to return.
* @param {string} request.pageToken
* A page token. Must be a value from
* [ListCollectionIdsResponse][google.firestore.v1beta1.ListCollectionIdsResponse].
* @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 an object representing string on 'data' event.
*/
listCollectionIdsStream(request?: protosTypes.google.firestore.v1beta1.IListCollectionIdsRequest, options?: gax.CallOptions | {}): Transform;
/**
* Terminate the GRPC channel and close the client.
*
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void>;
}

View File

@ -0,0 +1,841 @@
"use strict";
// Copyright 2019 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 });
const gax = require("google-gax");
const path = require("path");
const gapicConfig = require("./firestore_client_config.json");
const version = require('../../../package.json').version;
/**
* The Cloud Firestore service.
*
* This service exposes several types of comparable timestamps:
*
* * `create_time` - The time at which a document was created. Changes only
* when a document is deleted, then re-created. Increases in a strict
* monotonic fashion.
* * `update_time` - The time at which a document was last updated. Changes
* every time a document is modified. Does not change when a write results
* in no modifications. Increases in a strict monotonic fashion.
* * `read_time` - The time at which a particular state was observed. Used
* to denote a consistent snapshot of the database or the time at which a
* Document was observed to not exist.
* * `commit_time` - The time at which the writes in a transaction were
* committed. Any read with an equal or greater `read_time` is guaranteed
* to see the effects of the transaction.
* @class
* @memberof v1beta1
*/
class FirestoreClient {
/**
* Construct an instance of FirestoreClient.
*
* @param {object} [options] - The configuration object. See the subsequent
* parameters for more details.
* @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://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
*/
constructor(opts) {
this._descriptors = { page: {}, stream: {}, longrunning: {} };
this._terminated = false;
// Ensure that options include the service address and port.
const staticMembers = this.constructor;
const servicePath = opts && opts.servicePath
? opts.servicePath
: opts && opts.apiEndpoint
? opts.apiEndpoint
: staticMembers.servicePath;
const port = opts && opts.port ? opts.port : staticMembers.port;
if (!opts) {
opts = { servicePath, port };
}
opts.servicePath = opts.servicePath || servicePath;
opts.port = opts.port || port;
opts.clientConfig = opts.clientConfig || {};
const isBrowser = typeof window !== 'undefined';
if (isBrowser) {
opts.fallback = true;
}
// If we are in browser, we are already using fallback because of the
// "browser" field in package.json.
// But if we were explicitly requested to use fallback, let's do it now.
const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax;
// Create a `gaxGrpc` object, with any grpc-specific options
// sent to the client.
opts.scopes = this.constructor.scopes;
const gaxGrpc = new gaxModule.GrpcClient(opts);
// Save the auth object to the client, for use by other methods.
this.auth = gaxGrpc.auth;
// Determine the client header string.
const clientHeader = [`gax/${gaxModule.version}`, `gapic/${version}`];
if (typeof process !== 'undefined' && 'versions' in process) {
clientHeader.push(`gl-node/${process.versions.node}`);
}
else {
clientHeader.push(`gl-web/${gaxModule.version}`);
}
if (!opts.fallback) {
clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`);
}
if (opts.libName && opts.libVersion) {
clientHeader.push(`${opts.libName}/${opts.libVersion}`);
}
// Load the applicable protos.
// For Node.js, pass the path to JSON proto file.
// For browsers, pass the JSON content.
const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json');
const protos = gaxGrpc.loadProto(opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath);
// 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 gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'),
listCollectionIds: new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'collectionIds'),
};
// Some of the methods on this service provide streaming responses.
// Provide descriptors for these.
this._descriptors.stream = {
batchGetDocuments: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING),
runQuery: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING),
write: new gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING),
listen: new gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING),
};
// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings('google.firestore.v1beta1.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 = {};
// Put together the "service stub" for
// google.firestore.v1beta1.Firestore.
this.firestoreStub = gaxGrpc.createStub(opts.fallback
? protos.lookupService('google.firestore.v1beta1.Firestore')
: // tslint:disable-next-line no-any
protos.google.firestore.v1beta1.Firestore, opts);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const firestoreStubMethods = [
'getDocument',
'listDocuments',
'createDocument',
'updateDocument',
'deleteDocument',
'batchGetDocuments',
'beginTransaction',
'commit',
'rollback',
'runQuery',
'write',
'listen',
'listCollectionIds',
];
for (const methodName of firestoreStubMethods) {
const innerCallPromise = this.firestoreStub.then(stub => (...args) => {
if (this._terminated) {
return Promise.reject('The client has already been closed.');
}
return stub[methodName].apply(stub, args);
}, (err) => () => {
throw err;
});
const apiCall = gaxModule.createApiCall(innerCallPromise, defaults[methodName], this._descriptors.page[methodName] ||
this._descriptors.stream[methodName] ||
this._descriptors.longrunning[methodName]);
this._innerApiCalls[methodName] = (argument, callOptions, callback) => {
return apiCall(argument, callOptions, callback);
};
}
}
/**
* The DNS address for this API service.
*/
static get servicePath() {
return 'firestore.googleapis.com';
}
/**
* The DNS address for this API service - same as servicePath(),
* exists for compatibility reasons.
*/
static get apiEndpoint() {
return 'firestore.googleapis.com';
}
/**
* The port for this API service.
*/
static get port() {
return 443;
}
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
*/
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.
* @param {function(Error, string)} callback - the callback to
* be called with the current project Id.
*/
getProjectId(callback) {
if (callback) {
this.auth.getProjectId(callback);
return;
}
return this.auth.getProjectId();
}
/**
* Gets a single document.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. The resource name of the Document to get. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* @param {google.firestore.v1beta1.DocumentMask} request.mask
* The fields to return. If not set, returns all fields.
*
* If the 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 the document in a transaction.
* @param {google.protobuf.Timestamp} request.readTime
* Reads the version of the document at the given time.
* This may not be older than 60 seconds.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Document]{@link google.firestore.v1beta1.Document}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.getDocument(request, options, callback);
}
/**
* Creates a new document.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent resource. For example:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}`
* @param {string} request.collectionId
* Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`.
* @param {string} request.documentId
* The client-assigned document ID to use for this document.
*
* Optional. If not specified, an ID will be assigned by the service.
* @param {google.firestore.v1beta1.Document} request.document
* Required. The document to create. `name` must not be set.
* @param {google.firestore.v1beta1.DocumentMask} request.mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Document]{@link google.firestore.v1beta1.Document}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.createDocument(request, options, callback);
}
/**
* Updates or inserts a document.
*
* @param {Object} request
* The request object that will be sent.
* @param {google.firestore.v1beta1.Document} request.document
* Required. The updated document.
* Creates the document if it does not already exist.
* @param {google.firestore.v1beta1.DocumentMask} request.updateMask
* The fields to update.
* None of the field paths in the mask may contain a reserved name.
*
* If the document exists on the server and has fields not referenced in the
* mask, they are left unchanged.
* Fields referenced in the mask, but not present in the input document, are
* deleted from the document on the server.
* @param {google.firestore.v1beta1.DocumentMask} request.mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
* @param {google.firestore.v1beta1.Precondition} request.currentDocument
* An optional precondition on the document.
* The request will fail if this is set and not met by the target document.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Document]{@link google.firestore.v1beta1.Document}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
'document.name': request.document.name || '',
});
return this._innerApiCalls.updateDocument(request, options, callback);
}
/**
* Deletes a document.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. The resource name of the Document to delete. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* @param {google.firestore.v1beta1.Precondition} request.currentDocument
* An optional precondition on the document.
* The request will fail if this is set and not met by the target document.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.deleteDocument(request, options, callback);
}
/**
* Starts a new transaction.
*
* @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 {google.firestore.v1beta1.TransactionOptions} request.options
* The options for the transaction.
* Defaults to a read-write transaction.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [BeginTransactionResponse]{@link google.firestore.v1beta1.BeginTransactionResponse}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.beginTransaction(request, options, callback);
}
/**
* Commits a transaction, while optionally updating documents.
*
* @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 {number[]} request.writes
* The writes to apply.
*
* Always executed atomically and in order.
* @param {Buffer} request.transaction
* If set, applies all writes in this transaction, and commits it.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [CommitResponse]{@link google.firestore.v1beta1.CommitResponse}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.commit(request, options, callback);
}
/**
* Rolls back a transaction.
*
* @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 {Buffer} request.transaction
* Required. The transaction to roll back.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.rollback(request, options, callback);
}
/**
* 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.v1beta1.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.v1beta1.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 may not be older than 60 seconds.
* @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 [BatchGetDocumentsResponse]{@link google.firestore.v1beta1.BatchGetDocumentsResponse} on 'data' event.
*/
batchGetDocuments(request, options) {
request = request || {};
options = 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.v1beta1.StructuredQuery} request.structuredQuery
* A structured query.
* @param {Buffer} request.transaction
* Reads documents in a transaction.
* @param {google.firestore.v1beta1.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 may not be older than 60 seconds.
* @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 [RunQueryResponse]{@link google.firestore.v1beta1.RunQueryResponse} on 'data' event.
*/
runQuery(request, options) {
request = request || {};
options = options || {};
return this._innerApiCalls.runQuery(request, options);
}
/**
* Streams batches of document updates and deletes, in order.
*
* @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 [WriteRequest]{@link google.firestore.v1beta1.WriteRequest} for write() method, and
* will emit objects representing [WriteResponse]{@link google.firestore.v1beta1.WriteResponse} on 'data' event asynchronously.
*/
write(options) {
options = options || {};
return this._innerApiCalls.write(options);
}
/**
* Listens to changes.
*
* @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 [ListenRequest]{@link google.firestore.v1beta1.ListenRequest} for write() method, and
* will emit objects representing [ListenResponse]{@link google.firestore.v1beta1.ListenResponse} on 'data' event asynchronously.
*/
listen(options) {
options = options || {};
return this._innerApiCalls.listen({}, options);
}
/**
* Lists documents.
*
* @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
* Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`
* or `messages`.
* @param {number} request.pageSize
* The maximum number of documents to return.
* @param {string} request.pageToken
* The `next_page_token` value returned from a previous List request, if any.
* @param {string} request.orderBy
* The order to sort results by. For example: `priority desc, name`.
* @param {google.firestore.v1beta1.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.protobuf.Timestamp} request.readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
* @param {boolean} request.showMissing
* If the list should show missing documents. A missing document is a
* document that does not exist but has sub-documents. These documents will
* be returned with a key but will not have fields, [Document.create_time][google.firestore.v1beta1.Document.create_time],
* or [Document.update_time][google.firestore.v1beta1.Document.update_time] set.
*
* Requests with `show_missing` may not specify `where` or
* `order_by`.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [Document]{@link google.firestore.v1beta1.Document}.
* The client library support auto-pagination by default: it will call the API as many
* times as needed and will merge results from all the pages into this array.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of [Document]{@link google.firestore.v1beta1.Document} that corresponds to
* the one page received from the API server.
* If the second element is not null it contains the request object of type [ListDocumentsRequest]{@link google.firestore.v1beta1.ListDocumentsRequest}
* that can be used to obtain the next page of the results.
* If it is null, the next page does not exist.
* The third element contains the raw response received from the API server. Its type is
* [ListDocumentsResponse]{@link google.firestore.v1beta1.ListDocumentsResponse}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
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'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listDocuments(request, options, callback);
}
/**
* Equivalent to {@link listDocuments}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listDocuments} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @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
* Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`
* or `messages`.
* @param {number} request.pageSize
* The maximum number of documents to return.
* @param {string} request.pageToken
* The `next_page_token` value returned from a previous List request, if any.
* @param {string} request.orderBy
* The order to sort results by. For example: `priority desc, name`.
* @param {google.firestore.v1beta1.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.protobuf.Timestamp} request.readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
* @param {boolean} request.showMissing
* If the list should show missing documents. A missing document is a
* document that does not exist but has sub-documents. These documents will
* be returned with a key but will not have fields, [Document.create_time][google.firestore.v1beta1.Document.create_time],
* or [Document.update_time][google.firestore.v1beta1.Document.update_time] set.
*
* Requests with `show_missing` may not specify `where` or
* `order_by`.
* @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 an object representing [Document]{@link google.firestore.v1beta1.Document} on 'data' event.
*/
listDocumentsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listDocuments.createStream(this._innerApiCalls.listDocuments, request, callSettings);
}
/**
* Lists all the collection IDs underneath a document.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent document. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
* @param {number} request.pageSize
* The maximum number of results to return.
* @param {string} request.pageToken
* A page token. Must be a value from
* [ListCollectionIdsResponse][google.firestore.v1beta1.ListCollectionIdsResponse].
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of string.
* The client library support auto-pagination by default: it will call the API as many
* times as needed and will merge results from all the pages into this array.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of string that corresponds to
* the one page received from the API server.
* If the second element is not null it contains the request object of type [ListCollectionIdsRequest]{@link google.firestore.v1beta1.ListCollectionIdsRequest}
* that can be used to obtain the next page of the results.
* If it is null, the next page does not exist.
* The third element contains the raw response received from the API server. Its type is
* [ListCollectionIdsResponse]{@link google.firestore.v1beta1.ListCollectionIdsResponse}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*/
listCollectionIds(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'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listCollectionIds(request, options, callback);
}
/**
* Equivalent to {@link listCollectionIds}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listCollectionIds} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The parent document. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
* @param {number} request.pageSize
* The maximum number of results to return.
* @param {string} request.pageToken
* A page token. Must be a value from
* [ListCollectionIdsResponse][google.firestore.v1beta1.ListCollectionIdsResponse].
* @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 an object representing string on 'data' event.
*/
listCollectionIdsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listCollectionIds.createStream(this._innerApiCalls.listCollectionIds, request, callSettings);
}
/**
* Terminate the GRPC channel and close the client.
*
* The client will no longer be usable and all future behavior is undefined.
*/
close() {
if (!this._terminated) {
return this.firestoreStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
}
}
exports.FirestoreClient = FirestoreClient;
//# sourceMappingURL=firestore_client.js.map

View File

@ -0,0 +1,91 @@
{
"interfaces": {
"google.firestore.v1beta1.Firestore": {
"retry_codes": {
"non_idempotent": [],
"idempotent": [
"DEADLINE_EXCEEDED",
"UNAVAILABLE"
]
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 60000,
"rpc_timeout_multiplier": 1,
"max_rpc_timeout_millis": 60000,
"total_timeout_millis": 600000
}
},
"methods": {
"GetDocument": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ListDocuments": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"CreateDocument": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"UpdateDocument": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"DeleteDocument": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"BatchGetDocuments": {
"timeout_millis": 300000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"BeginTransaction": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"Commit": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"Rollback": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"RunQuery": {
"timeout_millis": 300000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"Write": {
"timeout_millis": 86400000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"Listen": {
"timeout_millis": 86400000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ListCollectionIds": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
}
}
}
}
}

View File

@ -0,0 +1,7 @@
[
"../../protos/google/firestore/v1beta1/common.proto",
"../../protos/google/firestore/v1beta1/document.proto",
"../../protos/google/firestore/v1beta1/write.proto",
"../../protos/google/firestore/v1beta1/query.proto",
"../../protos/google/firestore/v1beta1/firestore.proto"
]

View File

@ -0,0 +1,2 @@
import { FirestoreClient } from './firestore_client';
export { FirestoreClient };

View File

@ -0,0 +1,26 @@
"use strict";
// Copyright 2019 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 });
const firestore_client_1 = require("./firestore_client");
exports.FirestoreClient = firestore_client_1.FirestoreClient;
// Doing something really horrible for reverse compatibility with original JavaScript exports
const existingExports = module.exports;
module.exports = firestore_client_1.FirestoreClient;
module.exports = Object.assign(module.exports, existingExports);
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1,153 @@
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FieldPath } from './path';
/**
* Options to allow argument omission.
*
* @private
*/
export interface RequiredArgumentOptions {
optional?: boolean;
}
/**
* Options to limit the range of numbers.
*
* @private
*/
export interface NumericRangeOptions {
minValue?: number;
maxValue?: number;
}
/**
* Generates an error message to use with custom objects that cannot be
* serialized.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The value that failed serialization.
* @param path The field path that the object is assigned to.
*/
export declare function customObjectMessage(arg: string | number, value: unknown, path?: FieldPath): string;
/**
* Validates that 'value' is a function.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the function can be omitted.
*/
export declare function validateFunction(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void;
/**
* Validates that 'value' is an object.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the object can be omitted.
*/
export declare function validateObject(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void;
/**
* Validates that 'value' is a string.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the string can be omitted.
*/
export declare function validateString(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void;
/**
* Validates that 'value' is a host.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the host can be omitted.
*/
export declare function validateHost(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void;
/**
* Validates that 'value' is a boolean.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the boolean can be omitted.
*/
export declare function validateBoolean(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void;
/**
* Validates that 'value' is a number.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the number can be omitted.
*/
export declare function validateNumber(arg: string | number, value: unknown, options?: RequiredArgumentOptions & NumericRangeOptions): void;
/**
* Validates that 'value' is a integer.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the integer can be omitted.
*/
export declare function validateInteger(arg: string | number, value: unknown, options?: RequiredArgumentOptions & NumericRangeOptions): void;
/**
* Generates an error message to use with invalid arguments.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param expectedType The expected input type.
*/
export declare function invalidArgumentMessage(arg: string | number, expectedType: string): string;
/**
* Enforces the 'options.optional' constraint for 'value'.
*
* @private
* @param value The input to validate.
* @param options Whether the function can be omitted.
* @return Whether the object is omitted and is allowed to be omitted.
*/
export declare function validateOptional(value: unknown, options?: RequiredArgumentOptions): boolean;
/**
* Verifies that 'args' has at least 'minSize' elements.
*
* @private
* @param funcName The function name to use in the error message.
* @param args The array (or array-like structure) to verify.
* @param minSize The minimum number of elements to enforce.
* @throws if the expectation is not met.
*/
export declare function validateMinNumberOfArguments(funcName: string, args: IArguments | unknown[], minSize: number): void;
/**
* Verifies that 'args' has at most 'maxSize' elements.
*
* @private
* @param funcName The function name to use in the error message.
* @param args The array (or array-like structure) to verify.
* @param maxSize The maximum number of elements to enforce.
* @throws if the expectation is not met.
*/
export declare function validateMaxNumberOfArguments(funcName: string, args: IArguments, maxSize: number): void;
/**
* Validates that the provided named option equals one of the expected values.
*
* @param arg The argument name or argument index (for varargs methods).).
* @param value The input to validate.
* @param allowedValues A list of expected values.
* @param options Whether the input can be omitted.
* @private
*/
export declare function validateEnumValue(arg: string | number, value: unknown, allowedValues: string[], options?: RequiredArgumentOptions): void;

View File

@ -0,0 +1,298 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
const util_1 = require("./util");
/**
* Generates an error message to use with custom objects that cannot be
* serialized.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The value that failed serialization.
* @param path The field path that the object is assigned to.
*/
function customObjectMessage(arg, value, path) {
const fieldPathMessage = path ? ` (found in field "${path}")` : '';
if (util_1.isObject(value)) {
// We use the base class name as the type name as the sentinel classes
// returned by the public FieldValue API are subclasses of FieldValue. By
// using the base name, we reduce the number of special cases below.
const typeName = value.constructor.name;
switch (typeName) {
case 'DocumentReference':
case 'FieldPath':
case 'FieldValue':
case 'GeoPoint':
case 'Timestamp':
return (`${invalidArgumentMessage(arg, 'Firestore document')} Detected an object of type "${typeName}" that doesn't match the ` +
`expected instance${fieldPathMessage}. Please ensure that the ` +
'Firestore types you are using are from the same NPM package.)');
case 'Object':
return `${invalidArgumentMessage(arg, 'Firestore document')} Invalid use of type "${typeof value}" as a Firestore argument${fieldPathMessage}.`;
default:
return (`${invalidArgumentMessage(arg, 'Firestore document')} Couldn't serialize object of type "${typeName}"${fieldPathMessage}. Firestore doesn't support JavaScript ` +
'objects with custom prototypes (i.e. objects that were created ' +
'via the "new" operator).');
}
}
else {
return `${invalidArgumentMessage(arg, 'Firestore document')} Input is not a plain JavaScript object${fieldPathMessage}.`;
}
}
exports.customObjectMessage = customObjectMessage;
/**
* Validates that 'value' is a function.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the function can be omitted.
*/
function validateFunction(arg, value, options) {
if (!validateOptional(value, options)) {
if (!util_1.isFunction(value)) {
throw new Error(invalidArgumentMessage(arg, 'function'));
}
}
}
exports.validateFunction = validateFunction;
/**
* Validates that 'value' is an object.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the object can be omitted.
*/
function validateObject(arg, value, options) {
if (!validateOptional(value, options)) {
if (!util_1.isObject(value)) {
throw new Error(invalidArgumentMessage(arg, 'object'));
}
}
}
exports.validateObject = validateObject;
/**
* Validates that 'value' is a string.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the string can be omitted.
*/
function validateString(arg, value, options) {
if (!validateOptional(value, options)) {
if (typeof value !== 'string') {
throw new Error(invalidArgumentMessage(arg, 'string'));
}
}
}
exports.validateString = validateString;
/**
* Validates that 'value' is a host.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the host can be omitted.
*/
function validateHost(arg, value, options) {
if (!validateOptional(value, options)) {
validateString(arg, value);
const urlString = `http://${value}/`;
let parsed;
try {
parsed = new url_1.URL(urlString);
}
catch (e) {
throw new Error(invalidArgumentMessage(arg, 'host'));
}
if (parsed.search !== '' ||
parsed.pathname !== '/' ||
parsed.username !== '') {
throw new Error(invalidArgumentMessage(arg, 'host'));
}
}
}
exports.validateHost = validateHost;
/**
* Validates that 'value' is a boolean.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the boolean can be omitted.
*/
function validateBoolean(arg, value, options) {
if (!validateOptional(value, options)) {
if (typeof value !== 'boolean') {
throw new Error(invalidArgumentMessage(arg, 'boolean'));
}
}
}
exports.validateBoolean = validateBoolean;
/**
* Validates that 'value' is a number.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the number can be omitted.
*/
function validateNumber(arg, value, options) {
const min = options !== undefined && options.minValue !== undefined
? options.minValue
: -Infinity;
const max = options !== undefined && options.maxValue !== undefined
? options.maxValue
: Infinity;
if (!validateOptional(value, options)) {
if (typeof value !== 'number' || isNaN(value)) {
throw new Error(invalidArgumentMessage(arg, 'number'));
}
else if (value < min || value > max) {
throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`);
}
}
}
exports.validateNumber = validateNumber;
/**
* Validates that 'value' is a integer.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the integer can be omitted.
*/
function validateInteger(arg, value, options) {
const min = options !== undefined && options.minValue !== undefined
? options.minValue
: -Infinity;
const max = options !== undefined && options.maxValue !== undefined
? options.maxValue
: Infinity;
if (!validateOptional(value, options)) {
if (typeof value !== 'number' || isNaN(value) || value % 1 !== 0) {
throw new Error(invalidArgumentMessage(arg, 'integer'));
}
else if (value < min || value > max) {
throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`);
}
}
}
exports.validateInteger = validateInteger;
/**
* Generates an error message to use with invalid arguments.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param expectedType The expected input type.
*/
function invalidArgumentMessage(arg, expectedType) {
return `${formatArgumentName(arg)} is not a valid ${expectedType}.`;
}
exports.invalidArgumentMessage = invalidArgumentMessage;
/**
* Enforces the 'options.optional' constraint for 'value'.
*
* @private
* @param value The input to validate.
* @param options Whether the function can be omitted.
* @return Whether the object is omitted and is allowed to be omitted.
*/
function validateOptional(value, options) {
return (value === undefined && options !== undefined && options.optional === true);
}
exports.validateOptional = validateOptional;
/**
* Formats the given word as plural conditionally given the preceding number.
*
* @private
* @param num The number to use for formatting.
* @param str The string to format.
*/
function formatPlural(num, str) {
return `${num} ${str}` + (num === 1 ? '' : 's');
}
/**
* Creates a descriptive name for the provided argument name or index.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @return Either the argument name or its index description.
*/
function formatArgumentName(arg) {
return typeof arg === 'string'
? `Value for argument "${arg}"`
: `Element at index ${arg}`;
}
/**
* Verifies that 'args' has at least 'minSize' elements.
*
* @private
* @param funcName The function name to use in the error message.
* @param args The array (or array-like structure) to verify.
* @param minSize The minimum number of elements to enforce.
* @throws if the expectation is not met.
*/
function validateMinNumberOfArguments(funcName, args, minSize) {
if (args.length < minSize) {
throw new Error(`Function "${funcName}()" requires at least ` +
`${formatPlural(minSize, 'argument')}.`);
}
}
exports.validateMinNumberOfArguments = validateMinNumberOfArguments;
/**
* Verifies that 'args' has at most 'maxSize' elements.
*
* @private
* @param funcName The function name to use in the error message.
* @param args The array (or array-like structure) to verify.
* @param maxSize The maximum number of elements to enforce.
* @throws if the expectation is not met.
*/
function validateMaxNumberOfArguments(funcName, args, maxSize) {
if (args.length > maxSize) {
throw new Error(`Function "${funcName}()" accepts at most ` +
`${formatPlural(maxSize, 'argument')}.`);
}
}
exports.validateMaxNumberOfArguments = validateMaxNumberOfArguments;
/**
* Validates that the provided named option equals one of the expected values.
*
* @param arg The argument name or argument index (for varargs methods).).
* @param value The input to validate.
* @param allowedValues A list of expected values.
* @param options Whether the input can be omitted.
* @private
*/
function validateEnumValue(arg, value, allowedValues, options) {
if (!validateOptional(value, options)) {
const expectedDescription = [];
for (const allowed of allowedValues) {
if (allowed === value) {
return;
}
expectedDescription.push(allowed);
}
throw new Error(`${formatArgumentName(arg)} is invalid. Acceptable values are: ${expectedDescription.join(', ')}`);
}
}
exports.validateEnumValue = validateEnumValue;
//# sourceMappingURL=validate.js.map

View File

@ -0,0 +1,257 @@
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { google } from '../protos/firestore_v1_proto_api';
import { QueryDocumentSnapshot } from './document';
import { DocumentChange } from './document-change';
import { DocumentReference, Firestore, Query } from './index';
import { Timestamp } from './timestamp';
import { DocumentData, FirestoreDataConverter } from './types';
import api = google.firestore.v1;
/**
* @private
* @callback docsCallback
* @returns {Array.<QueryDocumentSnapshot>} An ordered list of documents.
*/
/**
* @private
* @callback changeCallback
* @returns {Array.<DocumentChange>} An ordered list of document
* changes.
*/
/**
* onSnapshot() callback that receives the updated query state.
*
* @private
* @callback watchSnapshotCallback
*
* @param {Timestamp} readTime The time at which this snapshot was obtained.
* @param {number} size The number of documents in the result set.
* @param {docsCallback} docs A callback that returns the ordered list of
* documents stored in this snapshot.
* @param {changeCallback} changes A callback that returns the list of
* changed documents since the last snapshot delivered for this watch.
*/
declare type DocumentComparator<T> = (l: QueryDocumentSnapshot<T>, r: QueryDocumentSnapshot<T>) => number;
/**
* Watch provides listen functionality and exposes the 'onSnapshot' observer. It
* can be used with a valid Firestore Listen target.
*
* @class
* @private
*/
declare abstract class Watch<T = DocumentData> {
readonly _converter: FirestoreDataConverter<T>;
protected readonly firestore: Firestore;
private readonly backoff;
private readonly requestTag;
/**
* Indicates whether we are interested in data from the stream. Set to false in the
* 'unsubscribe()' callback.
* @private
*/
private isActive;
/**
* The current stream to the backend.
* @private
*/
private currentStream;
/**
* The server assigns and updates the resume token.
* @private
*/
private resumeToken;
/**
* A map of document names to QueryDocumentSnapshots for the last sent snapshot.
* @private
*/
private docMap;
/**
* The accumulated map of document changes (keyed by document name) for the
* current snapshot.
* @private
*/
private changeMap;
/**
* The current state of the query results. *
* @private
*/
private current;
/**
* The sorted tree of QueryDocumentSnapshots as sent in the last snapshot.
* We only look at the keys.
* @private
*/
private docTree;
/**
* We need this to track whether we've pushed an initial set of changes,
* since we should push those even when there are no changes, if there
* aren't docs.
* @private
*/
private hasPushed;
private onNext;
private onError;
/**
* @private
* @hideconstructor
*
* @param firestore The Firestore Database client.
*/
constructor(firestore: Firestore, _converter?: FirestoreDataConverter<T>);
/** Returns a 'Target' proto denoting the target to listen on. */
protected abstract getTarget(resumeToken?: Uint8Array): api.ITarget;
/**
* Returns a comparator for QueryDocumentSnapshots that is used to order the
* document snapshots returned by this watch.
*/
protected abstract getComparator(): DocumentComparator<T>;
/**
* Starts a watch and attaches a listener for document change events.
*
* @private
* @param onNext A callback to be called every time a new snapshot is
* available.
* @param onError A callback to be called if the listen fails or is cancelled.
* No further callbacks will occur.
*
* @returns An unsubscribe function that can be called to cancel the snapshot
* listener.
*/
onSnapshot(onNext: (readTime: Timestamp, size: number, docs: () => Array<QueryDocumentSnapshot<T>>, changes: () => Array<DocumentChange<T>>) => void, onError: (error: Error) => void): () => void;
/**
* Returns the current count of all documents, including the changes from
* the current changeMap.
* @private
*/
private currentSize;
/**
* Splits up document changes into removals, additions, and updates.
* @private
*/
private extractCurrentChanges;
/**
* Helper to clear the docs on RESET or filter mismatch.
* @private
*/
private resetDocs;
/**
* Closes the stream and calls onError() if the stream is still active.
* @private
*/
private closeStream;
/**
* Re-opens the stream unless the specified error is considered permanent.
* Clears the change map.
* @private
*/
private maybeReopenStream;
/**
* Helper to restart the outgoing stream to the backend.
* @private
*/
private resetStream;
/**
* Initializes a new stream to the backend with backoff.
* @private
*/
private initStream;
/**
* Handles 'data' events and closes the stream if the response type is
* invalid.
* @private
*/
private onData;
/**
* Checks if the current target id is included in the list of target ids.
* If no targetIds are provided, returns true.
* @private
*/
private affectsTarget;
/**
* Assembles a new snapshot from the current set of changes and invokes the
* user's callback. Clears the current changes on completion.
* @private
*/
private pushSnapshot;
/**
* Applies a document delete to the document tree and the document map.
* Returns the corresponding DocumentChange event.
* @private
*/
private deleteDoc;
/**
* Applies a document add to the document tree and the document map. Returns
* the corresponding DocumentChange event.
* @private
*/
private addDoc;
/**
* Applies a document modification to the document tree and the document map.
* Returns the DocumentChange event for successful modifications.
* @private
*/
private modifyDoc;
/**
* Applies the mutations in changeMap to both the document tree and the
* document lookup map. Modified docMap in-place and returns the updated
* state.
* @private
*/
private computeSnapshot;
/**
* Determines whether a watch error is considered permanent and should not be
* retried. Errors that don't provide a GRPC error code are always considered
* transient in this context.
*
* @private
* @param error An error object.
* @return Whether the error is permanent.
*/
private isPermanentWatchError;
/**
* Determines whether we need to initiate a longer backoff due to system
* overload.
*
* @private
* @param error A GRPC Error object that exposes an error code.
* @return Whether we need to back off our retries.
*/
private isResourceExhaustedError;
}
/**
* Creates a new Watch instance to listen on DocumentReferences.
*
* @private
*/
export declare class DocumentWatch<T = DocumentData> extends Watch<T> {
private readonly ref;
constructor(firestore: Firestore, ref: DocumentReference<T>);
getComparator(): DocumentComparator<T>;
getTarget(resumeToken?: Uint8Array): google.firestore.v1.ITarget;
}
/**
* Creates a new Watch instance to listen on Queries.
*
* @private
*/
export declare class QueryWatch<T = DocumentData> extends Watch<T> {
private readonly query;
private comparator;
constructor(firestore: Firestore, query: Query<T>, converter?: FirestoreDataConverter<T>);
getComparator(): DocumentComparator<T>;
getTarget(resumeToken?: Uint8Array): google.firestore.v1.ITarget;
}
export {};

596
node_modules/@google-cloud/firestore/build/src/watch.js generated vendored Normal file
View File

@ -0,0 +1,596 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const assert = require("assert");
const rbtree = require("functional-red-black-tree");
const google_gax_1 = require("google-gax");
const backoff_1 = require("./backoff");
const document_1 = require("./document");
const document_change_1 = require("./document-change");
const logger_1 = require("./logger");
const path_1 = require("./path");
const timestamp_1 = require("./timestamp");
const types_1 = require("./types");
const util_1 = require("./util");
/*!
* Target ID used by watch. Watch uses a fixed target id since we only support
* one target per stream.
* @type {number}
*/
const WATCH_TARGET_ID = 0x1;
/*!
* Sentinel value for a document remove.
*/
// tslint:disable-next-line:no-any
const REMOVED = {};
/*!
* The change type for document change events.
*/
// tslint:disable-next-line:variable-name
const ChangeType = {
added: 'added',
modified: 'modified',
removed: 'removed',
};
/*!
* The comparator used for document watches (which should always get called with
* the same document).
*/
const DOCUMENT_WATCH_COMPARATOR = (doc1, doc2) => {
assert(doc1 === doc2, 'Document watches only support one document.');
return 0;
};
const EMPTY_FUNCTION = () => { };
/**
* Watch provides listen functionality and exposes the 'onSnapshot' observer. It
* can be used with a valid Firestore Listen target.
*
* @class
* @private
*/
class Watch {
/**
* @private
* @hideconstructor
*
* @param firestore The Firestore Database client.
*/
constructor(firestore, _converter = types_1.defaultConverter) {
this._converter = _converter;
/**
* Indicates whether we are interested in data from the stream. Set to false in the
* 'unsubscribe()' callback.
* @private
*/
this.isActive = true;
/**
* The current stream to the backend.
* @private
*/
this.currentStream = null;
/**
* The server assigns and updates the resume token.
* @private
*/
this.resumeToken = undefined;
/**
* A map of document names to QueryDocumentSnapshots for the last sent snapshot.
* @private
*/
this.docMap = new Map();
/**
* The accumulated map of document changes (keyed by document name) for the
* current snapshot.
* @private
*/
this.changeMap = new Map();
/**
* The current state of the query results. *
* @private
*/
this.current = false;
/**
* We need this to track whether we've pushed an initial set of changes,
* since we should push those even when there are no changes, if there
* aren't docs.
* @private
*/
this.hasPushed = false;
this.firestore = firestore;
this.backoff = new backoff_1.ExponentialBackoff();
this.requestTag = util_1.requestTag();
this.onNext = EMPTY_FUNCTION;
this.onError = EMPTY_FUNCTION;
}
/**
* Starts a watch and attaches a listener for document change events.
*
* @private
* @param onNext A callback to be called every time a new snapshot is
* available.
* @param onError A callback to be called if the listen fails or is cancelled.
* No further callbacks will occur.
*
* @returns An unsubscribe function that can be called to cancel the snapshot
* listener.
*/
onSnapshot(onNext, onError) {
assert(this.onNext === EMPTY_FUNCTION, 'onNext should not already be defined.');
assert(this.onError === EMPTY_FUNCTION, 'onError should not already be defined.');
assert(this.docTree === undefined, 'docTree should not already be defined.');
this.onNext = onNext;
this.onError = onError;
this.docTree = rbtree(this.getComparator());
this.initStream();
return () => {
logger_1.logger('Watch.onSnapshot', this.requestTag, 'Unsubscribe called');
// Prevent further callbacks.
this.isActive = false;
this.onNext = () => { };
this.onError = () => { };
if (this.currentStream) {
this.currentStream.end();
}
};
}
/**
* Returns the current count of all documents, including the changes from
* the current changeMap.
* @private
*/
currentSize() {
const changes = this.extractCurrentChanges(timestamp_1.Timestamp.now());
return this.docMap.size + changes.adds.length - changes.deletes.length;
}
/**
* Splits up document changes into removals, additions, and updates.
* @private
*/
extractCurrentChanges(readTime) {
const deletes = [];
const adds = [];
const updates = [];
this.changeMap.forEach((value, name) => {
if (value === REMOVED) {
if (this.docMap.has(name)) {
deletes.push(name);
}
}
else if (this.docMap.has(name)) {
value.readTime = readTime;
updates.push(value.build());
}
else {
value.readTime = readTime;
adds.push(value.build());
}
});
return { deletes, adds, updates };
}
/**
* Helper to clear the docs on RESET or filter mismatch.
* @private
*/
resetDocs() {
logger_1.logger('Watch.resetDocs', this.requestTag, 'Resetting documents');
this.changeMap.clear();
this.resumeToken = undefined;
this.docTree.forEach((snapshot) => {
// Mark each document as deleted. If documents are not deleted, they
// will be send again by the server.
this.changeMap.set(snapshot.ref.path, REMOVED);
});
this.current = false;
}
/**
* Closes the stream and calls onError() if the stream is still active.
* @private
*/
closeStream(err) {
if (this.currentStream) {
this.currentStream.end();
this.currentStream = null;
}
if (this.isActive) {
this.isActive = false;
logger_1.logger('Watch.closeStream', this.requestTag, 'Invoking onError: ', err);
this.onError(err);
}
}
/**
* Re-opens the stream unless the specified error is considered permanent.
* Clears the change map.
* @private
*/
maybeReopenStream(err) {
if (this.isActive && !this.isPermanentWatchError(err)) {
logger_1.logger('Watch.maybeReopenStream', this.requestTag, 'Stream ended, re-opening after retryable error: ', err);
this.changeMap.clear();
if (this.isResourceExhaustedError(err)) {
this.backoff.resetToMax();
}
this.initStream();
}
else {
this.closeStream(err);
}
}
/**
* Helper to restart the outgoing stream to the backend.
* @private
*/
resetStream() {
logger_1.logger('Watch.resetStream', this.requestTag, 'Restarting stream');
if (this.currentStream) {
this.currentStream.end();
this.currentStream = null;
}
this.initStream();
}
/**
* Initializes a new stream to the backend with backoff.
* @private
*/
initStream() {
this.backoff
.backoffAndWait()
.then(async () => {
if (!this.isActive) {
logger_1.logger('Watch.initStream', this.requestTag, 'Not initializing inactive stream');
return;
}
await this.firestore.initializeIfNeeded(this.requestTag);
const request = {};
request.database = this.firestore.formattedName;
request.addTarget = this.getTarget(this.resumeToken);
// Note that we need to call the internal _listen API to pass additional
// header values in readWriteStream.
return this.firestore
.requestStream('listen', request, this.requestTag)
.then(backendStream => {
if (!this.isActive) {
logger_1.logger('Watch.initStream', this.requestTag, 'Closing inactive stream');
backendStream.emit('end');
return;
}
logger_1.logger('Watch.initStream', this.requestTag, 'Opened new stream');
this.currentStream = backendStream;
this.currentStream.on('data', (proto) => {
this.onData(proto);
})
.on('error', err => {
if (this.currentStream === backendStream) {
this.currentStream = null;
this.maybeReopenStream(err);
}
})
.on('end', () => {
if (this.currentStream === backendStream) {
this.currentStream = null;
const err = new google_gax_1.GoogleError('Stream ended unexpectedly');
err.code = google_gax_1.Status.UNKNOWN;
this.maybeReopenStream(err);
}
});
this.currentStream.resume();
});
})
.catch(err => {
this.closeStream(err);
});
}
/**
* Handles 'data' events and closes the stream if the response type is
* invalid.
* @private
*/
onData(proto) {
if (proto.targetChange) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing target change');
const change = proto.targetChange;
const noTargetIds = !change.targetIds || change.targetIds.length === 0;
if (change.targetChangeType === 'NO_CHANGE') {
if (noTargetIds && change.readTime && this.current) {
// This means everything is up-to-date, so emit the current
// set of docs as a snapshot, if there were changes.
this.pushSnapshot(timestamp_1.Timestamp.fromProto(change.readTime), change.resumeToken);
}
}
else if (change.targetChangeType === 'ADD') {
if (WATCH_TARGET_ID !== change.targetIds[0]) {
this.closeStream(Error('Unexpected target ID sent by server'));
}
}
else if (change.targetChangeType === 'REMOVE') {
let code = google_gax_1.Status.INTERNAL;
let message = 'internal error';
if (change.cause) {
code = change.cause.code;
message = change.cause.message;
}
// @todo: Surface a .code property on the exception.
this.closeStream(new Error('Error ' + code + ': ' + message));
}
else if (change.targetChangeType === 'RESET') {
// Whatever changes have happened so far no longer matter.
this.resetDocs();
}
else if (change.targetChangeType === 'CURRENT') {
this.current = true;
}
else {
this.closeStream(new Error('Unknown target change type: ' + JSON.stringify(change)));
}
if (change.resumeToken &&
this.affectsTarget(change.targetIds, WATCH_TARGET_ID)) {
this.backoff.reset();
}
}
else if (proto.documentChange) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing change event');
// No other targetIds can show up here, but we still need to see
// if the targetId was in the added list or removed list.
const targetIds = proto.documentChange.targetIds || [];
const removedTargetIds = proto.documentChange.removedTargetIds || [];
let changed = false;
let removed = false;
for (let i = 0; i < targetIds.length; i++) {
if (targetIds[i] === WATCH_TARGET_ID) {
changed = true;
}
}
for (let i = 0; i < removedTargetIds.length; i++) {
if (removedTargetIds[i] === WATCH_TARGET_ID) {
removed = true;
}
}
const document = proto.documentChange.document;
const name = document.name;
const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name)
.relativeName;
if (changed) {
logger_1.logger('Watch.onData', this.requestTag, 'Received document change');
const ref = this.firestore.doc(relativeName);
const snapshot = new document_1.DocumentSnapshotBuilder(ref.withConverter(this._converter));
snapshot.fieldsProto = document.fields || {};
snapshot.createTime = timestamp_1.Timestamp.fromProto(document.createTime);
snapshot.updateTime = timestamp_1.Timestamp.fromProto(document.updateTime);
this.changeMap.set(relativeName, snapshot);
}
else if (removed) {
logger_1.logger('Watch.onData', this.requestTag, 'Received document remove');
this.changeMap.set(relativeName, REMOVED);
}
}
else if (proto.documentDelete || proto.documentRemove) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing remove event');
const name = (proto.documentDelete || proto.documentRemove).document;
const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name)
.relativeName;
this.changeMap.set(relativeName, REMOVED);
}
else if (proto.filter) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing filter update');
if (proto.filter.count !== this.currentSize()) {
// We need to remove all the current results.
this.resetDocs();
// The filter didn't match, so re-issue the query.
this.resetStream();
}
}
else {
this.closeStream(new Error('Unknown listen response type: ' + JSON.stringify(proto)));
}
}
/**
* Checks if the current target id is included in the list of target ids.
* If no targetIds are provided, returns true.
* @private
*/
affectsTarget(targetIds, currentId) {
if (targetIds === undefined || targetIds.length === 0) {
return true;
}
for (const targetId of targetIds) {
if (targetId === currentId) {
return true;
}
}
return false;
}
/**
* Assembles a new snapshot from the current set of changes and invokes the
* user's callback. Clears the current changes on completion.
* @private
*/
pushSnapshot(readTime, nextResumeToken) {
const appliedChanges = this.computeSnapshot(readTime);
if (!this.hasPushed || appliedChanges.length > 0) {
logger_1.logger('Watch.pushSnapshot', this.requestTag, 'Sending snapshot with %d changes and %d documents', String(appliedChanges.length), this.docTree.length);
// We pass the current set of changes, even if `docTree` is modified later.
const currentTree = this.docTree;
this.onNext(readTime, currentTree.length, () => currentTree.keys, () => appliedChanges);
this.hasPushed = true;
}
this.changeMap.clear();
this.resumeToken = nextResumeToken;
}
/**
* Applies a document delete to the document tree and the document map.
* Returns the corresponding DocumentChange event.
* @private
*/
deleteDoc(name) {
assert(this.docMap.has(name), 'Document to delete does not exist');
const oldDocument = this.docMap.get(name);
const existing = this.docTree.find(oldDocument);
const oldIndex = existing.index;
this.docTree = existing.remove();
this.docMap.delete(name);
return new document_change_1.DocumentChange(ChangeType.removed, oldDocument, oldIndex, -1);
}
/**
* Applies a document add to the document tree and the document map. Returns
* the corresponding DocumentChange event.
* @private
*/
addDoc(newDocument) {
const name = newDocument.ref.path;
assert(!this.docMap.has(name), 'Document to add already exists');
this.docTree = this.docTree.insert(newDocument, null);
const newIndex = this.docTree.find(newDocument).index;
this.docMap.set(name, newDocument);
return new document_change_1.DocumentChange(ChangeType.added, newDocument, -1, newIndex);
}
/**
* Applies a document modification to the document tree and the document map.
* Returns the DocumentChange event for successful modifications.
* @private
*/
modifyDoc(newDocument) {
const name = newDocument.ref.path;
assert(this.docMap.has(name), 'Document to modify does not exist');
const oldDocument = this.docMap.get(name);
if (!oldDocument.updateTime.isEqual(newDocument.updateTime)) {
const removeChange = this.deleteDoc(name);
const addChange = this.addDoc(newDocument);
return new document_change_1.DocumentChange(ChangeType.modified, newDocument, removeChange.oldIndex, addChange.newIndex);
}
return null;
}
/**
* Applies the mutations in changeMap to both the document tree and the
* document lookup map. Modified docMap in-place and returns the updated
* state.
* @private
*/
computeSnapshot(readTime) {
const changeSet = this.extractCurrentChanges(readTime);
const appliedChanges = [];
// Process the sorted changes in the order that is expected by our clients
// (removals, additions, and then modifications). We also need to sort the
// individual changes to assure that oldIndex/newIndex keep incrementing.
changeSet.deletes.sort((name1, name2) => {
// Deletes are sorted based on the order of the existing document.
return this.getComparator()(this.docMap.get(name1), this.docMap.get(name2));
});
changeSet.deletes.forEach(name => {
const change = this.deleteDoc(name);
appliedChanges.push(change);
});
changeSet.adds.sort(this.getComparator());
changeSet.adds.forEach(snapshot => {
const change = this.addDoc(snapshot);
appliedChanges.push(change);
});
changeSet.updates.sort(this.getComparator());
changeSet.updates.forEach(snapshot => {
const change = this.modifyDoc(snapshot);
if (change) {
appliedChanges.push(change);
}
});
assert(this.docTree.length === this.docMap.size, 'The update document ' +
'tree and document map should have the same number of entries.');
return appliedChanges;
}
/**
* Determines whether a watch error is considered permanent and should not be
* retried. Errors that don't provide a GRPC error code are always considered
* transient in this context.
*
* @private
* @param error An error object.
* @return Whether the error is permanent.
*/
isPermanentWatchError(error) {
if (error.code === undefined) {
logger_1.logger('Watch.isPermanentError', this.requestTag, 'Unable to determine error code: ', error);
return false;
}
switch (error.code) {
case google_gax_1.Status.ABORTED:
case google_gax_1.Status.CANCELLED:
case google_gax_1.Status.UNKNOWN:
case google_gax_1.Status.DEADLINE_EXCEEDED:
case google_gax_1.Status.RESOURCE_EXHAUSTED:
case google_gax_1.Status.INTERNAL:
case google_gax_1.Status.UNAVAILABLE:
case google_gax_1.Status.UNAUTHENTICATED:
return false;
default:
return true;
}
}
/**
* Determines whether we need to initiate a longer backoff due to system
* overload.
*
* @private
* @param error A GRPC Error object that exposes an error code.
* @return Whether we need to back off our retries.
*/
isResourceExhaustedError(error) {
return error.code === google_gax_1.Status.RESOURCE_EXHAUSTED;
}
}
/**
* Creates a new Watch instance to listen on DocumentReferences.
*
* @private
*/
class DocumentWatch extends Watch {
constructor(firestore, ref) {
super(firestore, ref._converter);
this.ref = ref;
}
getComparator() {
return DOCUMENT_WATCH_COMPARATOR;
}
getTarget(resumeToken) {
const formattedName = this.ref.formattedName;
return {
documents: {
documents: [formattedName],
},
targetId: WATCH_TARGET_ID,
resumeToken,
};
}
}
exports.DocumentWatch = DocumentWatch;
/**
* Creates a new Watch instance to listen on Queries.
*
* @private
*/
class QueryWatch extends Watch {
constructor(firestore, query, converter) {
super(firestore, converter);
this.query = query;
this.comparator = query.comparator();
}
getComparator() {
return this.query.comparator();
}
getTarget(resumeToken) {
const query = this.query.toProto();
return { query, targetId: WATCH_TARGET_ID, resumeToken };
}
}
exports.QueryWatch = QueryWatch;
//# sourceMappingURL=watch.js.map

View File

@ -0,0 +1,285 @@
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Firestore } from './index';
import { FieldPath } from './path';
import { DocumentReference } from './reference';
import { Timestamp } from './timestamp';
import { Precondition as PublicPrecondition, SetOptions, UpdateData } from './types';
import { DocumentData } from './types';
import { RequiredArgumentOptions } from './validate';
/**
* A WriteResult wraps the write time set by the Firestore servers on sets(),
* updates(), and creates().
*
* @class
*/
export declare class WriteResult {
private readonly _writeTime;
/**
* @hideconstructor
*
* @param _writeTime The time of the corresponding document write.
*/
constructor(_writeTime: Timestamp);
/**
* The write time as set by the Firestore servers.
*
* @type {Timestamp}
* @name WriteResult#writeTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({foo: 'bar'}).then(writeResult => {
* console.log(`Document written at: ${writeResult.writeTime.toDate()}`);
* });
*/
readonly writeTime: Timestamp;
/**
* Returns true if this `WriteResult` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return true if this `WriteResult` is equal to the provided value.
*/
isEqual(other: WriteResult): boolean;
}
/**
* A Firestore WriteBatch that can be used to atomically commit multiple write
* operations at once.
*
* @class
*/
export declare class WriteBatch {
private readonly _firestore;
private readonly _serializer;
/**
* An array of write operations that are executed as part of the commit. The
* resulting `api.IWrite` will be sent to the backend.
* @private
*/
private readonly _ops;
private _committed;
/**
* @hideconstructor
*
* @param firestore The Firestore Database client.
*/
constructor(firestore: Firestore);
/**
* Checks if this write batch has any pending operations.
*
* @private
*/
readonly isEmpty: boolean;
/**
* Throws an error if this batch has already been committed.
*
* @private
*/
private verifyNotCommitted;
/**
* Create a document with the provided object values. This will fail the batch
* if a document exists at its location.
*
* @param {DocumentReference} documentRef A reference to the document to be
* created.
* @param {T} data The object to serialize as the document.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.collection('col').doc();
*
* writeBatch.create(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
create<T>(documentRef: DocumentReference<T>, data: T): WriteBatch;
/**
* Deletes a document from the database.
*
* @param {DocumentReference} documentRef A reference to the document to be
* deleted.
* @param {Precondition=} precondition A precondition to enforce for this
* delete.
* @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
* document was last updated at lastUpdateTime. Fails the batch if the
* document doesn't exist or was last updated at a different time.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.delete(documentRef);
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
delete<T>(documentRef: DocumentReference<T>, precondition?: PublicPrecondition): WriteBatch;
/**
* Write to the document referred to by the provided
* [DocumentReference]{@link DocumentReference}.
* If the document does not exist yet, it will be created. If you pass
* [SetOptions]{@link SetOptions}., the provided data can be merged
* into the existing document.
*
* @param {DocumentReference} documentRef A reference to the document to be
* set.
* @param {T} data The object to serialize as the document.
* @param {SetOptions=} options An object to configure the set behavior.
* @param {boolean=} options.merge - If true, set() merges the values
* specified in its data argument. Fields omitted from this set() call
* remain untouched.
* @param {Array.<string|FieldPath>=} options.mergeFields - If provided,
* set() only replaces the specified field paths. Any field path that is not
* specified is ignored and remains untouched.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.set(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
set<T>(documentRef: DocumentReference<T>, data: T, options?: SetOptions): WriteBatch;
/**
* Update fields of the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document
* doesn't yet exist, the update fails and the entire batch will be rejected.
*
* The update() method accepts either an object with field paths encoded as
* keys and field values encoded as values, or a variable number of arguments
* that alternate between field paths and field values. Nested fields can be
* updated by providing dot-separated field path strings or by providing
* FieldPath objects.
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {DocumentReference} documentRef A reference to the document to be
* updated.
* @param {UpdateData|string|FieldPath} dataOrField An object
* containing the fields and values with which to update the document
* or the path of the first field to update.
* @param {
* ...(Precondition|*|string|FieldPath)} preconditionOrValues -
* An alternating list of field paths and values to update or a Precondition
* to restrict this update.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.update(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
update<T = DocumentData>(documentRef: DocumentReference<T>, dataOrField: UpdateData | string | FieldPath, ...preconditionOrValues: Array<{
lastUpdateTime?: Timestamp;
} | unknown | string | FieldPath>): WriteBatch;
/**
* Atomically commits all pending operations to the database and verifies all
* preconditions. Fails the entire write if any precondition is not met.
*
* @returns {Promise.<Array.<WriteResult>>} A Promise that resolves
* when this batch completes.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.set(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
commit(): Promise<WriteResult[]>;
/**
* Commit method that takes an optional transaction ID.
*
* @private
* @param commitOptions Options to use for this commit.
* @param commitOptions.transactionId The transaction ID of this commit.
* @param commitOptions.requestTag A unique client-assigned identifier for
* this request.
* @returns A Promise that resolves when this batch completes.
*/
commit_(commitOptions?: {
transactionId?: Uint8Array;
requestTag?: string;
}): Promise<WriteResult[]>;
/**
* Determines whether we should issue a transactional commit. On GCF, this
* happens after two minutes of idleness.
*
* @private
* @returns Whether to use a transaction.
*/
private _shouldCreateTransaction;
/**
* Resets the WriteBatch and dequeues all pending operations.
* @private
*/
_reset(): void;
}
/**
* Validates the use of 'value' as SetOptions and enforces that 'merge' is a
* boolean.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
* @throws if the input is not a valid SetOptions object.
*/
export declare function validateSetOptions(arg: string | number, value: unknown, options?: RequiredArgumentOptions): void;
/**
* Validates a JavaScript object for usage as a Firestore document.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param obj JavaScript object to validate.
* @param allowDeletes Whether to allow FieldValue.delete() sentinels.
* @throws when the object is invalid.
*/
export declare function validateDocumentData(arg: string | number, obj: unknown, allowDeletes: boolean): void;
/**
* Validates that a value can be used as field value during an update.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param val The value to verify.
* @param path The path to show in the error message.
*/
export declare function validateFieldValue(arg: string | number, val: unknown, path?: FieldPath): void;

View File

@ -0,0 +1,682 @@
"use strict";
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const assert = require("assert");
const document_1 = require("./document");
const logger_1 = require("./logger");
const path_1 = require("./path");
const reference_1 = require("./reference");
const serializer_1 = require("./serializer");
const timestamp_1 = require("./timestamp");
const util_1 = require("./util");
const validate_1 = require("./validate");
/*!
* Google Cloud Functions terminates idle connections after two minutes. After
* longer periods of idleness, we issue transactional commits to allow for
* retries.
*/
const GCF_IDLE_TIMEOUT_MS = 110 * 1000;
/**
* A WriteResult wraps the write time set by the Firestore servers on sets(),
* updates(), and creates().
*
* @class
*/
class WriteResult {
/**
* @hideconstructor
*
* @param _writeTime The time of the corresponding document write.
*/
constructor(_writeTime) {
this._writeTime = _writeTime;
}
/**
* The write time as set by the Firestore servers.
*
* @type {Timestamp}
* @name WriteResult#writeTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({foo: 'bar'}).then(writeResult => {
* console.log(`Document written at: ${writeResult.writeTime.toDate()}`);
* });
*/
get writeTime() {
return this._writeTime;
}
/**
* Returns true if this `WriteResult` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return true if this `WriteResult` is equal to the provided value.
*/
isEqual(other) {
return (this === other ||
(other instanceof WriteResult &&
this._writeTime.isEqual(other._writeTime)));
}
}
exports.WriteResult = WriteResult;
/**
* A Firestore WriteBatch that can be used to atomically commit multiple write
* operations at once.
*
* @class
*/
class WriteBatch {
/**
* @hideconstructor
*
* @param firestore The Firestore Database client.
*/
constructor(firestore) {
/**
* An array of write operations that are executed as part of the commit. The
* resulting `api.IWrite` will be sent to the backend.
* @private
*/
this._ops = [];
this._committed = false;
this._firestore = firestore;
this._serializer = new serializer_1.Serializer(firestore);
}
/**
* Checks if this write batch has any pending operations.
*
* @private
*/
get isEmpty() {
return this._ops.length === 0;
}
/**
* Throws an error if this batch has already been committed.
*
* @private
*/
verifyNotCommitted() {
if (this._committed) {
throw new Error('Cannot modify a WriteBatch that has been committed.');
}
}
/**
* Create a document with the provided object values. This will fail the batch
* if a document exists at its location.
*
* @param {DocumentReference} documentRef A reference to the document to be
* created.
* @param {T} data The object to serialize as the document.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.collection('col').doc();
*
* writeBatch.create(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
create(documentRef, data) {
reference_1.validateDocumentReference('documentRef', documentRef);
validateDocumentData('data', data, /* allowDeletes= */ false);
this.verifyNotCommitted();
const firestoreData = documentRef._converter.toFirestore(data);
const transform = document_1.DocumentTransform.fromObject(documentRef, firestoreData);
transform.validate();
const precondition = new document_1.Precondition({ exists: false });
const op = () => {
const document = document_1.DocumentSnapshot.fromObject(documentRef, firestoreData);
const write = !document.isEmpty || transform.isEmpty ? document.toProto() : null;
return {
write,
transform: transform.toProto(this._serializer),
precondition: precondition.toProto(),
};
};
this._ops.push(op);
return this;
}
/**
* Deletes a document from the database.
*
* @param {DocumentReference} documentRef A reference to the document to be
* deleted.
* @param {Precondition=} precondition A precondition to enforce for this
* delete.
* @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
* document was last updated at lastUpdateTime. Fails the batch if the
* document doesn't exist or was last updated at a different time.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.delete(documentRef);
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
delete(documentRef, precondition) {
reference_1.validateDocumentReference('documentRef', documentRef);
validateDeletePrecondition('precondition', precondition, { optional: true });
this.verifyNotCommitted();
const conditions = new document_1.Precondition(precondition);
const op = () => {
return {
write: {
delete: documentRef.formattedName,
},
precondition: conditions.toProto(),
};
};
this._ops.push(op);
return this;
}
/**
* Write to the document referred to by the provided
* [DocumentReference]{@link DocumentReference}.
* If the document does not exist yet, it will be created. If you pass
* [SetOptions]{@link SetOptions}., the provided data can be merged
* into the existing document.
*
* @param {DocumentReference} documentRef A reference to the document to be
* set.
* @param {T} data The object to serialize as the document.
* @param {SetOptions=} options An object to configure the set behavior.
* @param {boolean=} options.merge - If true, set() merges the values
* specified in its data argument. Fields omitted from this set() call
* remain untouched.
* @param {Array.<string|FieldPath>=} options.mergeFields - If provided,
* set() only replaces the specified field paths. Any field path that is not
* specified is ignored and remains untouched.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.set(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
set(documentRef, data, options) {
validateSetOptions('options', options, { optional: true });
const mergeLeaves = options && options.merge === true;
const mergePaths = options && options.mergeFields;
reference_1.validateDocumentReference('documentRef', documentRef);
let firestoreData = documentRef._converter.toFirestore(data);
validateDocumentData('data', firestoreData,
/* allowDeletes= */ !!(mergePaths || mergeLeaves));
this.verifyNotCommitted();
let documentMask;
if (mergePaths) {
documentMask = document_1.DocumentMask.fromFieldMask(options.mergeFields);
firestoreData = documentMask.applyTo(firestoreData);
}
const transform = document_1.DocumentTransform.fromObject(documentRef, firestoreData);
transform.validate();
const op = () => {
const document = document_1.DocumentSnapshot.fromObject(documentRef, firestoreData);
if (mergePaths) {
documentMask.removeFields(transform.fields);
}
else {
documentMask = document_1.DocumentMask.fromObject(firestoreData);
}
const hasDocumentData = !document.isEmpty || !documentMask.isEmpty;
let write;
if (!mergePaths && !mergeLeaves) {
write = document.toProto();
}
else if (hasDocumentData || transform.isEmpty) {
write = document.toProto();
write.updateMask = documentMask.toProto();
}
return {
write,
transform: transform.toProto(this._serializer),
};
};
this._ops.push(op);
return this;
}
/**
* Update fields of the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document
* doesn't yet exist, the update fails and the entire batch will be rejected.
*
* The update() method accepts either an object with field paths encoded as
* keys and field values encoded as values, or a variable number of arguments
* that alternate between field paths and field values. Nested fields can be
* updated by providing dot-separated field path strings or by providing
* FieldPath objects.
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {DocumentReference} documentRef A reference to the document to be
* updated.
* @param {UpdateData|string|FieldPath} dataOrField An object
* containing the fields and values with which to update the document
* or the path of the first field to update.
* @param {
* ...(Precondition|*|string|FieldPath)} preconditionOrValues -
* An alternating list of field paths and values to update or a Precondition
* to restrict this update.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.update(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
update(documentRef, dataOrField, ...preconditionOrValues) {
validate_1.validateMinNumberOfArguments('WriteBatch.update', arguments, 2);
reference_1.validateDocumentReference('documentRef', documentRef);
this.verifyNotCommitted();
const updateMap = new Map();
let precondition = new document_1.Precondition({ exists: true });
const argumentError = 'Update() requires either a single JavaScript ' +
'object or an alternating list of field/value pairs that can be ' +
'followed by an optional precondition.';
const usesVarargs = typeof dataOrField === 'string' || dataOrField instanceof path_1.FieldPath;
if (usesVarargs) {
try {
for (let i = 1; i < arguments.length; i += 2) {
if (i === arguments.length - 1) {
validateUpdatePrecondition(i, arguments[i]);
precondition = new document_1.Precondition(arguments[i]);
}
else {
path_1.validateFieldPath(i, arguments[i]);
// Unlike the `validateMinNumberOfArguments` invocation above, this
// validation can be triggered both from `WriteBatch.update()` and
// `DocumentReference.update()`. Hence, we don't use the fully
// qualified API name in the error message.
validate_1.validateMinNumberOfArguments('update', arguments, i + 1);
const fieldPath = path_1.FieldPath.fromArgument(arguments[i]);
validateFieldValue(i, arguments[i + 1], fieldPath);
updateMap.set(fieldPath, arguments[i + 1]);
}
}
}
catch (err) {
logger_1.logger('WriteBatch.update', null, 'Varargs validation failed:', err);
// We catch the validation error here and re-throw to provide a better
// error message.
throw new Error(`${argumentError} ${err.message}`);
}
}
else {
try {
validateUpdateMap('dataOrField', dataOrField);
validate_1.validateMaxNumberOfArguments('update', arguments, 3);
const data = dataOrField;
Object.keys(data).forEach(key => {
path_1.validateFieldPath(key, key);
updateMap.set(path_1.FieldPath.fromArgument(key), data[key]);
});
if (preconditionOrValues.length > 0) {
validateUpdatePrecondition('preconditionOrValues', preconditionOrValues[0]);
precondition = new document_1.Precondition(preconditionOrValues[0]);
}
}
catch (err) {
logger_1.logger('WriteBatch.update', null, 'Non-varargs validation failed:', err);
// We catch the validation error here and prefix the error with a custom
// message to describe the usage of update() better.
throw new Error(`${argumentError} ${err.message}`);
}
}
validateNoConflictingFields('dataOrField', updateMap);
const transform = document_1.DocumentTransform.fromUpdateMap(documentRef, updateMap);
transform.validate();
const documentMask = document_1.DocumentMask.fromUpdateMap(updateMap);
const op = () => {
const document = document_1.DocumentSnapshot.fromUpdateMap(documentRef, updateMap);
let write = null;
if (!document.isEmpty || !documentMask.isEmpty) {
write = document.toProto();
write.updateMask = documentMask.toProto();
}
return {
write,
transform: transform.toProto(this._serializer),
precondition: precondition.toProto(),
};
};
this._ops.push(op);
return this;
}
/**
* Atomically commits all pending operations to the database and verifies all
* preconditions. Fails the entire write if any precondition is not met.
*
* @returns {Promise.<Array.<WriteResult>>} A Promise that resolves
* when this batch completes.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.set(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
commit() {
return this.commit_();
}
/**
* Commit method that takes an optional transaction ID.
*
* @private
* @param commitOptions Options to use for this commit.
* @param commitOptions.transactionId The transaction ID of this commit.
* @param commitOptions.requestTag A unique client-assigned identifier for
* this request.
* @returns A Promise that resolves when this batch completes.
*/
async commit_(commitOptions) {
// Note: We don't call `verifyNotCommitted()` to allow for retries.
this._committed = true;
const tag = (commitOptions && commitOptions.requestTag) || util_1.requestTag();
await this._firestore.initializeIfNeeded(tag);
const database = this._firestore.formattedName;
// On GCF, we periodically force transactional commits to allow for
// request retries in case GCF closes our backend connection.
const explicitTransaction = commitOptions && commitOptions.transactionId;
if (!explicitTransaction && this._shouldCreateTransaction()) {
logger_1.logger('WriteBatch.commit', tag, 'Using transaction for commit');
return this._firestore
.request('beginTransaction', { database }, tag)
.then(resp => {
return this.commit_({ transactionId: resp.transaction });
});
}
const request = { database };
const writes = this._ops.map(op => op());
request.writes = [];
for (const req of writes) {
assert(req.write || req.transform, 'Either a write or transform must be set');
if (req.precondition) {
(req.write || req.transform).currentDocument = req.precondition;
}
if (req.write) {
request.writes.push(req.write);
}
if (req.transform) {
request.writes.push(req.transform);
}
}
logger_1.logger('WriteBatch.commit', tag, 'Sending %d writes', request.writes.length);
if (explicitTransaction) {
request.transaction = explicitTransaction;
}
return this._firestore
.request('commit', request, tag)
.then(resp => {
const writeResults = [];
if (request.writes.length > 0) {
assert(Array.isArray(resp.writeResults) &&
request.writes.length === resp.writeResults.length, `Expected one write result per operation, but got ${resp.writeResults.length} results for ${request.writes.length} operations.`);
const commitTime = timestamp_1.Timestamp.fromProto(resp.commitTime);
let offset = 0;
for (let i = 0; i < writes.length; ++i) {
const writeRequest = writes[i];
// Don't return two write results for a write that contains a
// transform, as the fact that we have to split one write
// operation into two distinct write requests is an implementation
// detail.
if (writeRequest.write && writeRequest.transform) {
// The document transform is always sent last and produces the
// latest update time.
++offset;
}
const writeResult = resp.writeResults[i + offset];
writeResults.push(new WriteResult(writeResult.updateTime
? timestamp_1.Timestamp.fromProto(writeResult.updateTime)
: commitTime));
}
}
return writeResults;
});
}
/**
* Determines whether we should issue a transactional commit. On GCF, this
* happens after two minutes of idleness.
*
* @private
* @returns Whether to use a transaction.
*/
_shouldCreateTransaction() {
if (!this._firestore._preferTransactions) {
return false;
}
if (this._firestore._lastSuccessfulRequest) {
const now = new Date().getTime();
return now - this._firestore._lastSuccessfulRequest > GCF_IDLE_TIMEOUT_MS;
}
return true;
}
/**
* Resets the WriteBatch and dequeues all pending operations.
* @private
*/
_reset() {
this._ops.splice(0);
this._committed = false;
}
}
exports.WriteBatch = WriteBatch;
/**
* Validates the use of 'value' as a Precondition and enforces that 'exists'
* and 'lastUpdateTime' use valid types.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate
* @param allowExists Whether to allow the 'exists' preconditions.
*/
function validatePrecondition(arg, value, allowExists) {
if (typeof value !== 'object' || value === null) {
throw new Error('Input is not an object.');
}
const precondition = value;
let conditions = 0;
if (precondition.exists !== undefined) {
++conditions;
if (!allowExists) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'precondition')} "exists" is not an allowed precondition.`);
}
if (typeof precondition.exists !== 'boolean') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'precondition')} "exists" is not a boolean.'`);
}
}
if (precondition.lastUpdateTime !== undefined) {
++conditions;
if (!(precondition.lastUpdateTime instanceof timestamp_1.Timestamp)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'precondition')} "lastUpdateTime" is not a Firestore Timestamp.`);
}
}
if (conditions > 1) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'precondition')} Input specifies more than one precondition.`);
}
}
/**
* Validates the use of 'value' as an update Precondition.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
*/
function validateUpdatePrecondition(arg, value, options) {
if (!validate_1.validateOptional(value, options)) {
validatePrecondition(arg, value, /* allowExists= */ false);
}
}
/**
* Validates the use of 'value' as a delete Precondition.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
*/
function validateDeletePrecondition(arg, value, options) {
if (!validate_1.validateOptional(value, options)) {
validatePrecondition(arg, value, /* allowExists= */ true);
}
}
/**
* Validates the use of 'value' as SetOptions and enforces that 'merge' is a
* boolean.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
* @throws if the input is not a valid SetOptions object.
*/
function validateSetOptions(arg, value, options) {
if (!validate_1.validateOptional(value, options)) {
if (!util_1.isObject(value)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} Input is not an object.`);
}
const setOptions = value;
if ('merge' in setOptions && typeof setOptions.merge !== 'boolean') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} "merge" is not a boolean.`);
}
if ('mergeFields' in setOptions) {
if (!Array.isArray(setOptions.mergeFields)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} "mergeFields" is not an array.`);
}
for (let i = 0; i < setOptions.mergeFields.length; ++i) {
try {
path_1.validateFieldPath(i, setOptions.mergeFields[i]);
}
catch (err) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} "mergeFields" is not valid: ${err.message}`);
}
}
}
if ('merge' in setOptions && 'mergeFields' in setOptions) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} You cannot specify both "merge" and "mergeFields".`);
}
}
}
exports.validateSetOptions = validateSetOptions;
/**
* Validates a JavaScript object for usage as a Firestore document.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param obj JavaScript object to validate.
* @param allowDeletes Whether to allow FieldValue.delete() sentinels.
* @throws when the object is invalid.
*/
function validateDocumentData(arg, obj, allowDeletes) {
if (!util_1.isPlainObject(obj)) {
throw new Error(validate_1.customObjectMessage(arg, obj));
}
for (const prop of Object.keys(obj)) {
serializer_1.validateUserInput(arg, obj[prop], 'Firestore document', {
allowDeletes: allowDeletes ? 'all' : 'none',
allowTransforms: true,
}, new path_1.FieldPath(prop));
}
}
exports.validateDocumentData = validateDocumentData;
/**
* Validates that a value can be used as field value during an update.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param val The value to verify.
* @param path The path to show in the error message.
*/
function validateFieldValue(arg, val, path) {
serializer_1.validateUserInput(arg, val, 'Firestore value', { allowDeletes: 'root', allowTransforms: true }, path);
}
exports.validateFieldValue = validateFieldValue;
/**
* Validates that the update data does not contain any ambiguous field
* definitions (such as 'a.b' and 'a').
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param data An update map with field/value pairs.
*/
function validateNoConflictingFields(arg, data) {
const fields = [];
data.forEach((value, key) => {
fields.push(key);
});
fields.sort((left, right) => left.compareTo(right));
for (let i = 1; i < fields.length; ++i) {
if (fields[i - 1].isPrefixOf(fields[i])) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'update map')} Field "${fields[i - 1]}" was specified multiple times.`);
}
}
}
/**
* Validates that a JavaScript object is a map of field paths to field values.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param obj JavaScript object to validate.
* @throws when the object is invalid.
*/
function validateUpdateMap(arg, obj) {
if (!util_1.isPlainObject(obj)) {
throw new Error(validate_1.customObjectMessage(arg, obj));
}
let isEmpty = true;
if (obj) {
for (const prop of Object.keys(obj)) {
isEmpty = false;
validateFieldValue(arg, obj[prop], new path_1.FieldPath(prop));
}
}
if (isEmpty) {
throw new Error('At least one field must be updated.');
}
}
//# sourceMappingURL=write-batch.js.map