-
Notifications
You must be signed in to change notification settings - Fork 1
/
dbService.js
110 lines (98 loc) · 2.72 KB
/
dbService.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
"use strict";
/**
* Import
*/
const csvParser = require("./helper/csv-parser");
const fs = require("fs");
const path = require("path");
/**
* Decalration const
*/
const DATA_MODEL_SOURCE = "./database/Data_Model_Gemtek.csv";
/**
* @brief return Promise for set one value
* @param {*} db
* @param {*} objectData
*/
function setOneValue(db, key, value) {
return new Promise((resolve, reject) => {
try {
// console.log("\n === dbService.setOneValue() ===");
// console.log(db);
// console.log(objectData);
db.findOne({ Parameter: key }, function (err, docs) {
// console.log(docs);
if (err) reject(`[ERROR] db.findOne() fail, ${err}`);
if (docs["Value"] != value) {
db.update(
{ _id: docs["_id"] },
{ $set: { Value: value } },
{},
function (error, numReplaced) {
if (error) reject(`[ERROR] db.update() fail, ${error}`);
resolve();
}
);
}
resolve();
});
} catch (err_) {
reject`[Error] dbService.setOneValue() fail, ${err_}`;
}
});
}
/**
* @brief Set value to DB
* @param {*} db : database instance
* @param {*} objectData : data want to change
* @returns
*/
function setValue(db, objectData) {
return new Promise(async (resolve, reject) => {
try {
console.log("\n === dbService.setValue() ===");
// console.log(db);
// console.log(objectData);
if (typeof objectData !== "object")
reject(`[ERROR] dbService.setValue() objectData is not in object type`);
// to DB
for (const [key, value] of Object.entries(objectData)) {
await setOneValue(db, key, value);
}
resolve();
} catch (err) {
reject(`[ERROR] dbService.setValue() fail, ${err}`);
}
});
}
// @TODO
function getValue(key) {
return value;
}
/**
* @brief Init DB if the .db empty
* @param {*} db : database instance
* @returns
*/
function initDB(db) {
return new Promise((resolve, reject) => {
try {
console.log("\n=== dbService.initDB ===");
// console.log(db);
// read csv file then write it to DB
const data = fs.readFileSync(DATA_MODEL_SOURCE);
if (path.parse(DATA_MODEL_SOURCE).ext.toLowerCase() === ".csv") {
const rows = csvParser.reduce(csvParser.parseCsv(data.toString()));
// Insert new DB
db.insert(rows, function (err, newDocs) {
if (err) reject(`[Error] db.insert() fail, ${err}`);
console.log("Make new Database -- Insert success");
resolve();
});
}
} catch (err) {
reject(`[Error] dbService.initDB() fail, ${err}`);
}
});
}
module.exports = { setValue, getValue, initDB };