forked from steadyequipment/node-firestore-backup
-
Notifications
You must be signed in to change notification settings - Fork 24
/
index.js
executable file
·374 lines (335 loc) · 10.7 KB
/
index.js
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/* @flow */
import commander from 'commander';
import colors from 'colors';
import process from 'process';
import fs from 'fs';
import Firebase from 'firebase-admin';
import mkdirp from 'mkdirp';
import path from 'path';
import stringify from 'json-stable-stringify';
import { getFireApp } from './lib/FirestoreFunctions';
import {
constructFirestoreDocumentObject,
constructDocumentObjectToBackup,
saveDocument
} from './lib/FirestoreDocument';
const accountCredentialsPathParamKey = 'accountCredentials';
const accountCredentialsPathParamDescription =
'Google Cloud account credentials JSON file';
const backupPathParamKey = 'backupPath';
const backupPathParamDescription = 'Path to store backup';
const restoreAccountCredentialsPathParamKey = 'restoreAccountCredentials';
const restoreAccountCredentialsPathParamDescription =
'Google Cloud account credentials JSON file for restoring documents';
const prettyPrintParamKey = 'prettyPrint';
const prettyPrintParamDescription = 'JSON backups done with pretty-printing';
const stableParamKey = 'stable';
const stableParamParamDescription = 'JSON backups done with stable-stringify';
const plainJSONBackupParamKey = 'plainJSONBackup';
const plainJSONBackupParamDescription = `JSON backups done without preserving any type information
- Lacks full fidelity restore to Firestore
- Can be used for other export purposes`;
const packagePath = __dirname.includes('/build') ? '..' : '.';
let version = 'N/A - unable to read package.json file';
try {
version = require(`${packagePath}/package.json`).version;
} catch (requireError) {}
// The data to be restored can replace the existing ones
// or they can be merged with existing ones
const mergeData = false;
commander
.version(version)
.option(
'-a, --' + accountCredentialsPathParamKey + ' <path>',
accountCredentialsPathParamDescription
)
.option('-B, --' + backupPathParamKey + ' <path>', backupPathParamDescription)
.option(
'-a2, --' + restoreAccountCredentialsPathParamKey + ' <path>',
restoreAccountCredentialsPathParamDescription
)
.option('-P, --' + prettyPrintParamKey, prettyPrintParamDescription)
.option('-S, --' + stableParamKey, stableParamParamDescription)
.option('-J, --' + plainJSONBackupParamKey, plainJSONBackupParamDescription)
.parse(process.argv);
const accountCredentialsPath = commander[accountCredentialsPathParamKey];
if (accountCredentialsPath && !fs.existsSync(accountCredentialsPath)) {
console.log(
colors.bold(colors.red('Account credentials file does not exist: ')) +
colors.bold(accountCredentialsPath)
);
commander.help();
process.exit(1);
}
const backupPath = commander[backupPathParamKey];
if (!backupPath) {
console.log(
colors.bold(colors.red('Missing: ')) +
colors.bold(backupPathParamKey) +
' - ' +
backupPathParamDescription
);
commander.help();
process.exit(1);
}
const restoreAccountCredentialsPath =
commander[restoreAccountCredentialsPathParamKey];
if (
restoreAccountCredentialsPath &&
!fs.existsSync(restoreAccountCredentialsPath)
) {
console.log(
colors.bold(
colors.red('Restore account credentials file does not exist: ')
) + colors.bold(restoreAccountCredentialsPath)
);
commander.help();
process.exit(1);
}
const prettyPrint =
commander[prettyPrintParamKey] !== undefined &&
commander[prettyPrintParamKey] !== null;
const stable =
commander[stableParamKey] !== undefined &&
commander[stableParamKey] !== null;
const plainJSONBackup =
commander[plainJSONBackupParamKey] !== undefined &&
commander[plainJSONBackupParamKey] !== null;
const accountApp: Object = accountCredentialsPath
? getFireApp(accountCredentialsPath)
: {};
try {
mkdirp.sync(backupPath);
} catch (error) {
console.log(
colors.bold(colors.red('Unable to create backup path: ')) +
colors.bold(backupPath) +
' - ' +
error
);
process.exit(1);
}
const restoreAccountApp: Object = restoreAccountCredentialsPath
? getFireApp(restoreAccountCredentialsPath)
: {};
// from: https://hackernoon.com/functional-javascript-resolving-promises-sequentially-7aac18c4431e
const promiseSerial = funcs => {
return funcs.reduce((promise, func) => {
return promise.then(result => {
return func().then(() => {
return Array.prototype.concat.bind(result);
});
});
}, Promise.resolve([]));
};
const backupDocument = (
document: Object,
backupPath: string,
logPath: string
): Promise<any> => {
console.log(
"Backing up Document '" +
logPath +
document.id +
"'" +
(plainJSONBackup === true
? ' with -J --plainJSONBackup'
: ' with type information')
);
try {
mkdirp.sync(backupPath);
let fileContents: string;
const documentBackup =
plainJSONBackup === true
? document.data()
: constructDocumentObjectToBackup(document.data());
if (prettyPrint === true) {
if (stable === true) {
fileContents = stringify(documentBackup, { space: 2 });
} else {
fileContents = JSON.stringify(documentBackup, null, 2);
}
} else {
if (stable === true) {
fileContents = stringify(documentBackup);
} else {
fileContents = JSON.stringify(documentBackup);
}
}
fs.writeFileSync(backupPath + '/' + document.id + '.json', fileContents);
return document.ref.getCollections().then(collections => {
return promiseSerial(
collections.map(collection => {
return () => {
return backupCollection(
collection,
backupPath + '/' + collection.id,
logPath + document.id + '/'
);
};
})
);
});
} catch (error) {
console.log(
colors.bold(
colors.red(
"Unable to create backup path or write file, skipping backup of Document '" +
document.id +
"': "
)
) +
colors.bold(backupPath) +
' - ' +
error
);
return Promise.reject(error);
}
};
const backupCollection = (
collection: Object,
backupPath: string,
logPath: string
): Promise<void> => {
console.log("Backing up Collection '" + logPath + collection.id + "'");
// TODO: implement feature to skip certain Collections
// if (collection.id.toLowerCase().indexOf('geotrack') > 0) {
// console.log(`Skipping ${collection.id}`);
// return promiseSerial([() => Promise.resolve()]);
// }
try {
mkdirp.sync(backupPath);
return collection.get().then(snapshots => {
const backupFunctions = [];
snapshots.forEach(document => {
backupFunctions.push(() => {
const backupDocumentPromise = backupDocument(
document,
backupPath + '/' + document.id,
logPath + collection.id + '/'
);
restoreDocument(logPath + collection.id, document);
return backupDocumentPromise;
});
});
return promiseSerial(backupFunctions);
});
} catch (error) {
console.log(
colors.bold(
colors.red(
"Unable to create backup path, skipping backup of Collection '" +
collection.id +
"': "
)
) +
colors.bold(backupPath) +
' - ' +
error
);
return Promise.reject(error);
}
};
const accountDb = accountCredentialsPath ? accountApp.firestore() : null;
export const restoreAccountDb = restoreAccountCredentialsPath
? restoreAccountApp.firestore()
: null;
const restoreDocument = (collectionName: string, document: Object) => {
const restoreMsg = `Restoring to collection ${collectionName} document ${
document.id
}`;
console.log(`${restoreMsg}...`);
return Promise.resolve(
// TODO: use saveDocument using merge as an option
!restoreAccountDb
? null
: restoreAccountDb
.collection(collectionName)
.doc(document.id)
.set(document.data())
).catch(error => {
console.log(
colors.bold(colors.red(`Error! ${restoreMsg}` + ' - ' + error))
);
});
};
const restoreBackup = (
path: string,
restoreAccountDb: Object,
promisesChain: Array = []
) => {
const promisesResult = promisesChain;
fs.readdirSync(path).forEach(element => {
const elementPath = `${path}/${element}`;
const stats = fs.statSync(elementPath);
const isDirectory = stats.isDirectory();
if (isDirectory) {
const folderPromises = restoreBackup(
elementPath,
restoreAccountDb,
promisesChain
);
promisesResult.concat(folderPromises);
} else {
const documentId = path.split('/').pop();
const pathWithoutId = path.substr(0, path.lastIndexOf('/'));
// remove from the path the global backupPath
const pathWithoutBackupPath = pathWithoutId.replace(backupPath, '');
const collectionName = pathWithoutBackupPath;
const restoreMsg = `Restoring to collection ${collectionName} document ${elementPath}`;
console.log(`${restoreMsg}`);
const documentDataValue = fs.readFileSync(elementPath);
const documentData = constructFirestoreDocumentObject(
JSON.parse(documentDataValue),
{ firestore: restoreAccountDb }
);
promisesResult.push(
saveDocument(
restoreAccountDb,
collectionName,
documentId,
documentData,
{ merge: mergeData }
).catch(saveError => {
const saveErrorMsg = `\n !!! Uh-Oh, error saving collection ${collectionName} document ${elementPath}`;
console.error(saveErrorMsg, saveError);
if (!saveError.metadata) {
saveError.metadata = {};
}
saveError.metadata.collectionName = collectionName;
saveError.metadata.document = elementPath;
return Promise.reject(saveError);
})
);
}
});
return promisesResult;
};
const mustExecuteBackup: boolean =
!!accountDb || (!!accountDb && !!restoreAccountDb);
if (mustExecuteBackup) {
accountDb.getCollections().then(collections => {
return promiseSerial(
collections.map(collection => {
return () => {
return backupCollection(
collection,
backupPath + '/' + collection.id,
'/'
);
};
})
);
});
}
const mustExecuteRestore: boolean =
!accountDb && !!restoreAccountDb && !!backupPath;
if (mustExecuteRestore) {
const promisesRes = restoreBackup(backupPath, restoreAccountDb);
Promise.all(promisesRes)
.then(restoration => console.log(`\n -- Restore Completed! -- \n`))
.catch(errors => {
console.log(`\n !!! Restore NOT Complete; there were Errors !!!\n`);
(errors instanceof Array ? errors : [errors]).map(console.error);
});
}