This repository has been archived by the owner on May 5, 2023. It is now read-only.
/
cli.js
98 lines (88 loc) · 3.56 KB
/
cli.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
#!/usr/bin/env node
const fs = require('fs');
const path = require("path");
const { MongoClient } = require('mongodb');
const args = process.argv.slice(2);
const examplePath = path.resolve(__dirname, 'example.json');
switch (args[0]) {
case '-h':
case '--help':
case undefined:
console.log('\n\nRefer to https://github.com/federico-ntr/mongo-json-setter/blob/main/README.md for instructions on how to use this utility.\n')
break;
case '--example':
mongoSetup(examplePath);
break;
default:
mongoSetup(args[0]);
}
function mongoSetup(json) {
fs.readFile(json, 'utf8', (err, data) => {
//Handle errors
if(err) {
switch (err.code) {
case 'ENOENT':
console.log('\n\nNo such file or directory. Please, select a valid JSON file.\n');
break;
case 'EISDIR':
console.log('\n\nThe specified file is a directory. Please, select a valid JSON file\n');
break;
default:
console.error(err);
}
return;
}
//Parse JSON
let config;
try {
config = JSON.parse(data);
} catch (e) {
if (e instanceof SyntaxError) console.error('\n\nThe specified file is not a valid JSON file.\n')
return;
}
const host = config.host;
const port = config.port;
const db_name = config.db_name;
const username = config.username;
const password = config.password;
const userDb = config.userDb;
const collections = config.collections;
//console.log(username + ' ' + password + ' ' + (username !== undefined && password !== undefined));
const url = (username !== undefined && password !== undefined)
? `mongodb://${username}:${password}@${host}:${port}/${db_name}?authSource=${userDb}`
: `mongodb://${host}:${port}/${db_name}`;
//Connect to DB
MongoClient.connect(url, {useUnifiedTopology: true}, (err, db) => {
if (err) throw err;
const dbo = db.db(db_name);
console.log("Database created");
for (const [i, collection] of collections.entries()) {
dbo.createCollection(collection.name, (err, coll) => {
if (err) {
switch (err.code) {
case 13:
console.log('You need to be authenticated to create collections in this database.');
break;
default:
console.log(err.code);
throw err;
}
}
console.log("Collection created!");
for (const [k, document] of collection.documents.entries()) {
for (const key in document) {
if (Object.prototype.hasOwnProperty.call(document[key], '$date')) {
document[key] = new Date(Date.parse(document[key].$date));
}
}
coll.insertOne(document, (err, res) => {
if (err) throw err;
if (i === config.collections.length - 1 && k === collection.documents.length - 1)
db.close();
});
}
});
}
});
});
}