-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
export.ts
75 lines (69 loc) · 2.73 KB
/
export.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
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
import {
batchExecutor,
isLikeDocument,
isRootOfDatabase,
safelyGetCollectionsSnapshot,
safelyGetDocumentReferences,
} from './firestore-helpers';
import * as admin from 'firebase-admin';
import {serializeSpecialTypes} from './helpers';
const exportData = async (startingRef: admin.firestore.Firestore |
FirebaseFirestore.DocumentReference |
FirebaseFirestore.CollectionReference, logs = false) => {
if (isLikeDocument(startingRef)) {
const collectionsPromise = getCollections(startingRef, logs);
let dataPromise: Promise<any>;
if (isRootOfDatabase(startingRef)) {
dataPromise = Promise.resolve({});
} else {
dataPromise = (<FirebaseFirestore.DocumentReference>startingRef).get()
.then(snapshot => snapshot.data())
.then(data => serializeSpecialTypes(data));
}
return await batchExecutor([collectionsPromise, dataPromise]).then(res => {
return {'__collections__': res[0], ...res[1]};
});
} else {
return await getDocuments(<FirebaseFirestore.CollectionReference>startingRef, logs);
}
};
const getCollections = async (startingRef: admin.firestore.Firestore | FirebaseFirestore.DocumentReference, logs = false) => {
const collectionNames: Array<string> = [];
const collectionPromises: Array<Promise<any>> = [];
const collectionsSnapshot = await safelyGetCollectionsSnapshot(startingRef, logs);
collectionsSnapshot.map((collectionRef: FirebaseFirestore.CollectionReference) => {
collectionNames.push(collectionRef.id);
collectionPromises.push(getDocuments(collectionRef, logs));
});
const results = await batchExecutor(collectionPromises);
const zipped: any = {};
results.map((res: any, idx: number) => {
zipped[collectionNames[idx]] = res;
});
return zipped;
};
const getDocuments = async (collectionRef: FirebaseFirestore.CollectionReference, logs = false) => {
logs && console.log(`Retrieving documents from ${collectionRef.path}`);
const results: any = {};
const documentPromises: Array<Promise<object>> = [];
const allDocuments = await safelyGetDocumentReferences(collectionRef, logs);
allDocuments.forEach((doc) => {
documentPromises.push(new Promise(async (resolve) => {
const docSnapshot = await doc.get();
const docDetails: any = {};
if (docSnapshot.exists) {
docDetails[docSnapshot.id] = serializeSpecialTypes(docSnapshot.data());
} else {
docDetails[docSnapshot.id] = {};
}
docDetails[docSnapshot.id]['__collections__'] = await getCollections(docSnapshot.ref, logs);
resolve(docDetails);
}));
});
(await batchExecutor(documentPromises))
.forEach((res: any) => {
Object.keys(res).map(key => (<any>results)[key] = res[key]);
});
return results;
};
export default exportData;