Spaces:
Paused
Paused
File size: 10,925 Bytes
4c921aa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | "use strict";
/**
* Copyright 2024 Google LLC. 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 });
exports.CollectionReference = void 0;
const path_1 = require("../path");
const util_1 = require("../util");
const write_batch_1 = require("../write-batch");
const types_1 = require("../types");
const query_1 = require("./query");
const document_reference_1 = require("./document-reference");
const query_options_1 = require("./query-options");
const trace_util_1 = require("../telemetry/trace-util");
/**
* A CollectionReference object can be used for adding documents, getting
* document references, and querying for documents (using the methods
* inherited from [Query]{@link Query}).
*
* @class CollectionReference
* @extends Query
*/
class CollectionReference extends query_1.Query {
/**
* @private
*
* @param firestore The Firestore Database client.
* @param path The Path of this collection.
*/
constructor(firestore, path, converter) {
super(firestore, query_options_1.QueryOptions.forCollectionQuery(path, converter));
}
/**
* Returns a resource path for this collection.
* @private
* @internal
*/
get _resourcePath() {
return this._queryOptions.parentPath.append(this._queryOptions.collectionId);
}
/**
* The last path element of the referenced collection.
*
* @type {string}
* @name CollectionReference#id
* @readonly
*
* @example
* ```
* let collectionRef = firestore.collection('col/doc/subcollection');
* console.log(`ID of the subcollection: ${collectionRef.id}`);
* ```
*/
get id() {
return this._queryOptions.collectionId;
}
/**
* A reference to the containing Document if this is a subcollection, else
* null.
*
* @type {DocumentReference|null}
* @name CollectionReference#parent
* @readonly
*
* @example
* ```
* let collectionRef = firestore.collection('col/doc/subcollection');
* let documentRef = collectionRef.parent;
* console.log(`Parent name: ${documentRef.path}`);
* ```
*/
get parent() {
if (this._queryOptions.parentPath.isDocument) {
return new document_reference_1.DocumentReference(this.firestore, this._queryOptions.parentPath);
}
return null;
}
/**
* A string representing the path of the referenced collection (relative
* to the root of the database).
*
* @type {string}
* @name CollectionReference#path
* @readonly
*
* @example
* ```
* let collectionRef = firestore.collection('col/doc/subcollection');
* console.log(`Path of the subcollection: ${collectionRef.path}`);
* ```
*/
get path() {
return this._resourcePath.relativeName;
}
/**
* Retrieves the list of documents in this collection.
*
* The document references returned may include references to "missing
* documents", i.e. document locations that have no document present but
* which contain subcollections with documents. Attempting to read such a
* document reference (e.g. via `.get()` or `.onSnapshot()`) will return a
* `DocumentSnapshot` whose `.exists` property is false.
*
* @return {Promise<DocumentReference[]>} The list of documents in this
* collection.
*
* @example
* ```
* let collectionRef = firestore.collection('col');
*
* return collectionRef.listDocuments().then(documentRefs => {
* return firestore.getAll(...documentRefs);
* }).then(documentSnapshots => {
* for (let documentSnapshot of documentSnapshots) {
* if (documentSnapshot.exists) {
* console.log(`Found document with data: ${documentSnapshot.id}`);
* } else {
* console.log(`Found missing document: ${documentSnapshot.id}`);
* }
* }
* });
* ```
*/
listDocuments() {
return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_COL_REF_LIST_DOCUMENTS, () => {
const tag = (0, util_1.requestTag)();
return this.firestore.initializeIfNeeded(tag).then(() => {
const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(this.firestore.projectId, this.firestore.databaseId);
const request = {
parent: parentPath.formattedName,
collectionId: this.id,
showMissing: true,
mask: { fieldPaths: [] },
};
return this.firestore
.request('listDocuments', request, tag)
.then(documents => {
// Note that the backend already orders these documents by name,
// so we do not need to manually sort them.
return documents.map(doc => {
const path = path_1.QualifiedResourcePath.fromSlashSeparatedString(doc.name);
return this.doc(path.id);
});
});
});
});
}
/**
* Gets a [DocumentReference]{@link DocumentReference} instance that
* refers to the document at the specified path. If no path is specified, an
* automatically-generated unique ID will be used for the returned
* DocumentReference.
*
* @param {string=} documentPath A slash-separated path to a document.
* @returns {DocumentReference} The `DocumentReference`
* instance.
*
* @example
* ```
* let collectionRef = firestore.collection('col');
* let documentRefWithName = collectionRef.doc('doc');
* let documentRefWithAutoId = collectionRef.doc();
* console.log(`Reference with name: ${documentRefWithName.path}`);
* console.log(`Reference with auto-id: ${documentRefWithAutoId.path}`);
* ```
*/
doc(documentPath) {
if (arguments.length === 0) {
documentPath = (0, util_1.autoId)();
}
else {
(0, path_1.validateResourcePath)('documentPath', documentPath);
}
const path = this._resourcePath.append(documentPath);
if (!path.isDocument) {
throw new Error(`Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`);
}
return new document_reference_1.DocumentReference(this.firestore, path, this._queryOptions.converter);
}
/**
* Add a new document to this collection with the specified data, assigning
* it a document ID automatically.
*
* @param {DocumentData} data An Object containing the data for the new
* document.
* @throws {Error} If the provided input is not a valid Firestore document.
* @returns {Promise.<DocumentReference>} A Promise resolved with a
* [DocumentReference]{@link DocumentReference} pointing to the
* newly created document.
*
* @example
* ```
* let collectionRef = firestore.collection('col');
* collectionRef.add({foo: 'bar'}).then(documentReference => {
* console.log(`Added document with name: ${documentReference.id}`);
* });
* ```
*/
add(data) {
return this._firestore._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_COL_REF_ADD, () => {
const firestoreData = this._queryOptions.converter.toFirestore(data);
(0, write_batch_1.validateDocumentData)('data', firestoreData,
/*allowDeletes=*/ false, this._allowUndefined);
const documentRef = this.doc();
return documentRef.create(data).then(() => documentRef);
});
}
/**
* Returns true if this `CollectionReference` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `CollectionReference` is equal to the
* provided value.
*/
isEqual(other) {
return (this === other ||
(other instanceof CollectionReference && super.isEqual(other)));
}
/**
* Applies a custom data converter to this CollectionReference, allowing you
* to use your own custom model objects with Firestore. When you call add() on
* the returned CollectionReference instance, the provided converter will
* convert between Firestore data of type `NewDbModelType` and your custom
* type `NewAppModelType`.
*
* Using the converter allows you to specify generic type arguments when
* storing and retrieving objects from Firestore.
*
* Passing in `null` as the converter parameter removes the current
* converter.
*
* @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(
* snapshot: FirebaseFirestore.QueryDocumentSnapshot
* ): Post {
* const data = snapshot.data();
* 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
* }
*
* ```
* @param {FirestoreDataConverter | null} converter Converts objects to and
* from Firestore. Passing in `null` removes the current converter.
* @return A CollectionReference that uses the provided converter.
*/
withConverter(converter) {
return new CollectionReference(this.firestore, this._resourcePath, converter !== null && converter !== void 0 ? converter : (0, types_1.defaultConverter)());
}
}
exports.CollectionReference = CollectionReference;
//# sourceMappingURL=collection-reference.js.map |