forked from dalenguyen/firestore-import-export
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.js
101 lines (85 loc) · 2.63 KB
/
import.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
const fs = require('fs');
const YAML = require('js-yaml');
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccountKey.json");
const fileName = process.argv[2];
const reDate = new RegExp(/^date/);
const reGeo = new RegExp(/^geo/);
let dateArray = process.argv.filter(item => item.match(reDate))[0];
let geoArray = process.argv.filter(item => item.match(reGeo))[0];
if (dateArray) {
dateArray = dateArray.split('=')[1].split(',');
}
if (geoArray) {
geoArray = geoArray.split('=')[1].split(',');
}
// You should replace databaseURL with your own
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://ionic-firestore-dn.firebaseio.com"
});
const db = admin.firestore();
db.settings({ timestampsInSnapshots: true });
fs.readFile(fileName, 'utf8', function(err, data){
if(err){
return console.log(err);
}
// Turn string from file to an Array
if (fileName.endsWith('yaml') || fileName.endsWith('yml')) {
dataArray = YAML.safeLoad(data);
} else {
dataArray = JSON.parse(data);
}
updateCollection(dataArray);
})
async function updateCollection(dataArray){
for(const index in dataArray){
const collectionName = index;
for(const doc in dataArray[index]){
if(dataArray[index].hasOwnProperty(doc)){
await startUpdating(collectionName, doc, dataArray[index][doc]);
}
}
}
}
function startUpdating(collectionName, doc, data){
// convert date from unixtimestamp
let parameterValid = true;
// Enter date value
if(typeof dateArray !== 'undefined') {
dateArray.map(date => {
if (data.hasOwnProperty(date)) {
data[date] = new Date(data[date]._seconds * 1000);
} else {
console.log('Please check your date parameters!!!', dateArray);
parameterValid = false;
}
});
}
// Enter geo value
if(typeof geoArray !== 'undefined') {
geoArray.map(geo => {
if(data.hasOwnProperty(geo)) {
data[geo] = new admin.firestore.GeoPoint(data[geo]._latitude, data[geo]._longitude);
} else {
console.log('Please check your geo parameters!!!', geoArray);
parameterValid = false;
}
})
}
if(parameterValid) {
return new Promise(resolve => {
db.collection(collectionName).doc(doc)
.set(data)
.then(() => {
console.log(`${doc} is imported successfully to firestore!`);
resolve('Data wrote!');
})
.catch(error => {
console.log(error);
});
});
} else {
console.log(`${doc} is not imported to firestore. Please check your parameters!`);
}
}