-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirebase-utility.ts
163 lines (147 loc) · 5.6 KB
/
firebase-utility.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
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
const firebaseAdmin = require('firebase-admin');
const serviceAccount = './credentials.json';
const firebaseUrl = 'https://pe-athleticinjuries.firebaseio.com';
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(require(serviceAccount)),
databaseURL: firebaseUrl
});
const firestore = firebaseAdmin.firestore();
// Source: https://leechy.dev/firestore-move
export const copyDoc = async (
collectionFrom: string,
docIdFrom: string,
collectionTo: string,
docIdTo: string,
addData: any = {},
recursive = false,
): Promise<boolean> => {
// document reference
const docRef = firestore.collection(collectionFrom).doc(docIdFrom);
// copy the document
const docData = await docRef
.get()
.then((doc) => doc.exists && doc.data())
.catch((error) => {
console.error('Error reading document', `${collectionFrom}/${docIdFrom}`, JSON.stringify(error));
// throw new functions.https.HttpsError('not-found', 'Copying document was not read');
});
if (docData) {
// document exists, create the new item
await firestore
.collection(collectionTo)
.doc(docIdTo)
.set({ ...docData, ...addData })
.catch((error) => {
console.error('Error creating document', `${collectionTo}/${docIdTo}`, JSON.stringify(error));
// throw new functions.https.HttpsError(
// 'data-loss',
// 'Data was not copied properly to the target collection, please try again.',
// );
});
// if copying of the subcollections is needed
if (recursive) {
// subcollections
const subcollections = await docRef.getCollections();
for await (const subcollectionRef of subcollections) {
const subcollectionPath = `${collectionFrom}/${docIdFrom}/${subcollectionRef.id}`;
// get all the documents in the collection
return await subcollectionRef
.get()
.then(async (snapshot) => {
const docs = snapshot.docs;
for await (const doc of docs) {
await copyDoc(subcollectionPath, doc.id, `${collectionTo}/${docIdTo}/${subcollectionRef.id}`, doc.id, true);
}
return true;
})
.catch((error) => {
console.error('Error reading subcollection', subcollectionPath, JSON.stringify(error));
// throw new functions.https.HttpsError(
// 'data-loss',
// 'Data was not copied properly to the target collection, please try again.',
// );
});
}
}
return true;
}
return false;
};
export const deleteDoc = async (docPath: string): Promise<boolean> => {
// document reference
const docRef = firestore.doc(docPath);
// subcollections
const subcollections = await docRef.getCollections();
for await (const subcollectionRef of subcollections) {
await subcollectionRef
.get()
.then(async (snapshot) => {
const docs = snapshot.docs;
for await (const doc of docs) {
await deleteDoc(`${docPath}/${subcollectionRef.id}/${doc.id}`);
}
return true;
})
.catch((error) => {
console.error('Error reading subcollection', `${docPath}/${subcollectionRef.id}`, JSON.stringify(error));
return false;
});
}
// when all subcollections are deleted, delete the document itself
return docRef
.delete()
.then(() => true)
.catch((error) => {
console.error('Error deleting document', docPath, JSON.stringify(error));
return false;
});
};
export const moveDoc = async (
collectionFrom: string,
docIdFrom: string,
collectionTo: string,
docIdTo: string,
addData?: any,
): Promise<boolean | Error> => {
// copy the organisation document
const copied = await copyDoc(collectionFrom, docIdFrom, collectionTo, docIdTo, addData, true);
// if copy was successful, delete the original
if (copied) {
await deleteDoc(`${collectionFrom}/${docIdFrom}`);
return true;
}
// throw new functions.https.HttpsError(
// 'data-loss',
// 'Data was not copied properly to the target collection, please try again.',
// );
};
export const generateDocId = (
length: number = 20,
chars: string = "#aA"
) => {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
return result;
}
export const updateDocId = async (collectionId: string = "body-parts") => {
const colRef = await firestore.collection(collectionId).get();
for await (const doc of colRef.docs) {
const subcollections = await firestore.doc(collectionId + "/" + doc.id).getCollections();
for await (const subcollectionRef of subcollections) {
const subdocs = await subcollectionRef.get();
for await (const sd of subdocs.docs) {
if (sd.id.length <= 3) {
const id = generateDocId(20 - (sd.id.length+1))
moveDoc(subcollectionRef.path, sd.id, subcollectionRef.path, sd.id + "_" + id)
}
}
}
}
};
updateDocId();
moveDoc("body-parts/test921923/stretching", "t2", "body-parts/test921923/stretching", "t5");