-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.ts
44 lines (41 loc) · 1.36 KB
/
helpers.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
import * as path from "path";
import * as admin from "firebase-admin";
import {
Query,
QueryDocumentSnapshot,
CollectionReference
} from "@google-cloud/firestore";
export function getDb(pathToFbKey: string, projectId: string) {
const firebaseKey = require(pathToFbKey[0] == "/" || pathToFbKey[0] == "~"
? pathToFbKey
: path.resolve(path.join(process.cwd(), pathToFbKey)));
if (firebaseKey.project_id !== projectId) {
throw Error(
`Gave projectId ${projectId} but path to firebase key credentials was for ${
firebaseKey.project_id
}`
);
}
const app = admin.initializeApp({
credential: admin.credential.cert(firebaseKey),
databaseURL: `https://${firebaseKey.project_id}.firebaseio.com`
});
return app.firestore();
}
export async function fetchEntireCollection(
collection: CollectionReference
): Promise<QueryDocumentSnapshot[]> {
let backup: any[] = [];
let curCollectionView: Query = collection;
let docs: QueryDocumentSnapshot[] = [];
while (true) {
const snapshot = await curCollectionView.get();
const fetchSize = snapshot.docs.length;
if (fetchSize === 0) break;
console.log(`Fetched ${fetchSize}`);
docs = docs.concat(snapshot.docs as QueryDocumentSnapshot[]);
const last = snapshot.docs[snapshot.docs.length - 1];
curCollectionView = collection.startAfter(last);
}
return docs;
}