forked from grahamearley/FirestoreGoogleAppsScript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
GetBatch.ts
49 lines (43 loc) · 1.49 KB
/
GetBatch.ts
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
/**
* Gets multiple documents.
*/
class GetBatch {
#documents: string[] = [];
/**
* A container for multiple reads
* @param {Firestore} _firestore the parent instance
*/
constructor(private readonly _firestore: Firestore) {}
/**
* Add a document to the retrive list
* @param {string} docPath The document to fetch
* @returns This `WriteBatch` instance. Used for chaining method calls.
*/
add(docPath: string): GetBatch {
this.#documents.push(docPath);
return this;
}
/**
* Get the requested documents
* @param {string[]} mask Field mask for document read, applies to all documents
* @returns {Document[]} The found files only
*/
get(mask?: string[]): Document[] {
const request = new Request(this._firestore.baseUrl, this._firestore.authToken);
request.route('batchGet');
const payload: FirestoreAPI.BatchGetDocumentsRequest = {
documents: this.#documents.map((doc) => this._firestore.basePath + doc),
mask: mask && { fieldPaths: mask },
};
const responseObj = request.post<FirestoreAPI.BatchGetDocumentsResponse[]>(undefined, payload);
// Filter out results without documents and unwrap document fields
const documents = responseObj.reduce((docs: Document[], docItem: FirestoreAPI.BatchGetDocumentsResponse) => {
if (docItem.found) {
const doc = new Document(docItem.found, { readTime: docItem.readTime } as Document);
docs.push(doc);
}
return docs;
}, []);
return documents;
}
}