-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
76 lines (57 loc) · 1.88 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
const mongodb = require("mongodb"), client = mongodb.MongoClient;
const path = require("path");
const readJSON = require("read-json");
const booksFile = path.resolve(__dirname, "../../data/books.json");
const categoriesFile = path.resolve(__dirname, "../../data/categories.json");
const USER = process.env.MONGO_USER || "admin";
const PSWD = process.env.MONGO_PASSWORD || "admin";
const DOMAIN = process.env.MONGO_DOMAIN || "localhost";
const PORT = process.env.MONGO_PORT || "27017";
const DB = process.env.MONGO_DB || "mongo-db";
const connectionString = `mongodb://${DOMAIN}:${PORT}/${DB}`;
let promise;
let db;
const dbConnector = connectionString => {
if (promise) {
return promise;
}
console.log(`Mongo connect: ${connectionString}`);
promise = client.connect(connectionString).then(function(database) {
db = database;
return db;
});
return promise;
};
const collection = name => {
return dbConnector(connectionString).then(db => db.collection(name));
};
const fetch = filename => {
return new Promise((resolve, reject) =>
readJSON(filename, (error, elements) => {
if (error) {
return reject(error);
}
resolve(elements);
})
);
};
const init = (type, file) => {
return collection(type).then(col => col.find().toArray()).then(elementsDB => {
if (!elementsDB.length) {
console.log(`MongoDB collection (${type}) not found, import...`);
return fetch(file).then(elements => {
return col.insertMany(elements);
});
}
console.log(`MongoDB collection (${type}) found...`);
return Promise.resolve();
});
};
const initBooks = () => init("books", booksFile);
const initCategories = () => init("categories", categoriesFile);
exports.dbConnector = dbConnector;
exports.collection = collection;
exports.init = () => {
console.log("MongoDB init...");
return Promise.all([initBooks(), initCategories()]);
};