Commit 60e58a54 by Beebuddy Builder

add mongodb

1 parent 72612251
...@@ -22,6 +22,8 @@ ...@@ -22,6 +22,8 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"dotenv": "^8.2.0" "dotenv": "^8.2.0",
"moment": "2.29.1",
"mongodb": "3.1.8"
} }
} }
...@@ -3,10 +3,12 @@ ...@@ -3,10 +3,12 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.ENV = exports.Utils = void 0; exports.connectMongo = exports.ENV = exports.Utils = void 0;
var _dotenv = _interopRequireDefault(require("dotenv")); var _dotenv = _interopRequireDefault(require("dotenv"));
var _connect_db = _interopRequireDefault(require("./utils/mongodb/connect_db"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
...@@ -45,4 +47,6 @@ exports.Utils = Utils; ...@@ -45,4 +47,6 @@ exports.Utils = Utils;
var ENV = { var ENV = {
env: process.env env: process.env
}; };
exports.ENV = ENV; exports.ENV = ENV;
\ No newline at end of file var connectMongo = new _connect_db.default();
exports.connectMongo = connectMongo;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _moment = _interopRequireDefault(require("moment"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var _default = {
log: function log() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var req = args[0];
if (_typeof(req) === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log("\x1B[0m".concat(getTime(), " INFO ").concat(toString(args).join(''), "\x1B[0m"));
},
info: function info() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var req = args[0];
if (_typeof(req) === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log("\x1B[36m".concat(getTime(), " INFO ").concat(toString(args).join(''), "\x1B[0m"));
},
error: function error() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var req = args[0];
if (_typeof(req) === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log("\x1B[31m".concat(getTime(), " ERROR ").concat(toString(args).join(''), "\x1B[0m"));
},
warning: function warning() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
var req = args[0];
if (_typeof(req) === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log("\x1B[33m".concat(getTime(), " INFO ").concat(toString(args).join(''), "\x1B[0m"));
},
success: function success() {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
var req = args[0];
if (_typeof(req) === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log("\x1B[32m".concat(getTime(), " INFO ").concat(toString(args).join(''), "\x1B[0m"));
},
magenta: function magenta() {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
var req = args[0];
if (_typeof(req) === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log("\x1B[35m".concat(getTime(), " INFO ").concat(toString(args).join(''), "\x1B[0m"));
},
random: function random() {
for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
args[_key7] = arguments[_key7];
}
var req = args[0];
if (_typeof(req) === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log(toString(args).join('').split('').map(function (item) {
return '\x1b[' + randomColor() + 'm' + item + '\x1b[0m';
}).join('') + '\n');
},
db: function db() {
for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
args[_key8] = arguments[_key8];
}
var req = args[0];
if (_typeof(req) === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log("\x1B[35m".concat(getTime(), " INFO [Database Message] ").concat(toString(args).join(''), "\x1B[0m"));
}
/**
* Random color not duplicate next character
*/
};
exports.default = _default;
var tempColor = null;
var randomColor = function randomColor() {
if (tempColor != null) {
var rand = Math.floor(Math.random() * (37 - 31) + 31);
if (rand != tempColor) {
tempColor = rand;
return rand;
} else {
return randomColor();
}
} else {
tempColor = Math.floor(Math.random() * (37 - 31) + 31);
return tempColor;
}
};
var toString = function toString(list) {
return list.map(function (item) {
return item.constructor.name == 'Object' || item.constructor.name == 'Array' ? JSON.stringify(item) : item;
});
};
var getTime = function getTime() {
return (0, _moment.default)().format("YYYY-MM-DD HH:mm:ss:SSS");
};
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = {
DMA5_DMA_OBJECT: "dma5_dma_object",
DMA5_CONFIG: "dma5_config",
DMA5_BUILDER_ENV: "dma5_builder_env",
DMA5_PUBLISH_QUEUE: "dma5_publish_queue",
DMA5_CARD_PROTOTYPE: "dma5_card_prototype",
DMA_SCREEN: "app_ui_config",
DMA_STORYBOARD: "story_board_config",
DMA_STORYBOARD_LIST: "storyboard_storyboardlist",
DMA_STORYBOARD_GROUP: "storyboard_groups",
DMA_MASTER_NATIVE_INPUT: 'screen_native_input_type'
};
exports.default = _default;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _collections = _interopRequireDefault(require("./collections"));
var dbActions = _interopRequireWildcard(require("./db_config/action"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ConnectMongo = function ConnectMongo() {
_classCallCheck(this, ConnectMongo);
dbActions.openConnection();
};
var _default = ConnectMongo;
exports.default = _default;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.openConnection = openConnection;
exports.find = find;
exports.findOne = findOne;
exports.insertOne = insertOne;
exports.updateOne = updateOne;
exports.updateMany = updateMany;
exports.deleteMany = deleteMany;
exports.findOneAndUpdate = findOneAndUpdate;
exports.aggregate = aggregate;
exports.CreateSession = CreateSession;
var _mongodb = require("mongodb");
var _config_db = _interopRequireDefault(require("./config_db"));
var _logger = _interopRequireDefault(require("../../logger/logger"));
var _app_config = _interopRequireDefault(require("../../../config/app_config"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
/**
* @type {MongoClient}
*/
var mongo = null;
var TAG = "[ConnectMongo] ";
function openConnection() {
return _openConnection.apply(this, arguments);
}
/**
* Select * From
* @param {String} collectionName
* @param {*} queryCondition
* @param {Object} filter
* @returns {Promise<Array>}
*/
function _openConnection() {
_openConnection = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee() {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return _mongodb.MongoClient.connect(_config_db.default.DB_CONNECT_STR, {
useNewUrlParser: true,
useUnifiedTopology: true,
poolSize: _app_config.default.config.db_connection_pool_size
});
case 3:
mongo = _context.sent;
_logger.default.info("".concat(TAG, "::::::::::::::: Mongo DB is connected ::::::::::::::::"));
_context.next = 10;
break;
case 7:
_context.prev = 7;
_context.t0 = _context["catch"](0);
_logger.default.error("".concat(TAG, "::::::::::::::: Cannot connect to Mongo DB ::::::::::::::::\n").concat(_context.t0));
case 10:
case "end":
return _context.stop();
}
}
}, _callee, null, [[0, 7]]);
}));
return _openConnection.apply(this, arguments);
}
function find(_x) {
return _find.apply(this, arguments);
}
/**
* Select * From Where Only One Data
* @param {String} collectionName
* @param {*} queryCondition
*/
function _find() {
_find = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(collectionName) {
var queryCondition,
filter,
dbo,
resultObject,
_args2 = arguments;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
queryCondition = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {};
filter = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : {};
_context2.prev = 2;
if (!(mongo === null || !mongo.isConnected())) {
_context2.next = 6;
break;
}
_context2.next = 6;
return openConnection();
case 6:
dbo = mongo.db(_config_db.default.DB_NAME);
_context2.next = 9;
return dbo.collection(collectionName).find(queryCondition, {
projection: _objectSpread({}, filter)
}).toArray();
case 9:
resultObject = _context2.sent;
_logger.default.db("Find data from " + collectionName + " Success.");
return _context2.abrupt("return", resultObject);
case 14:
_context2.prev = 14;
_context2.t0 = _context2["catch"](2);
throw _context2.t0;
case 17:
case "end":
return _context2.stop();
}
}
}, _callee2, null, [[2, 14]]);
}));
return _find.apply(this, arguments);
}
function findOne(_x2) {
return _findOne.apply(this, arguments);
}
/**
* Insert One Data
* @param {String} collectionName
* @param {OptionalId<Object>} data
* @param {ClientSession} session
*/
function _findOne() {
_findOne = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee3(collectionName) {
var queryCondition,
dbo,
resultObject,
_args3 = arguments;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
queryCondition = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : {};
_context3.prev = 1;
if (!(mongo === null || !mongo.isConnected())) {
_context3.next = 5;
break;
}
_context3.next = 5;
return openConnection();
case 5:
dbo = mongo.db(_config_db.default.DB_NAME);
_context3.next = 8;
return dbo.collection(collectionName).findOne(queryCondition, {
projection: {
_id: 0
}
});
case 8:
resultObject = _context3.sent;
_logger.default.db("Find data from " + collectionName + " Success.");
return _context3.abrupt("return", resultObject);
case 13:
_context3.prev = 13;
_context3.t0 = _context3["catch"](1);
throw _context3.t0;
case 16:
case "end":
return _context3.stop();
}
}
}, _callee3, null, [[1, 13]]);
}));
return _findOne.apply(this, arguments);
}
function insertOne(_x3) {
return _insertOne.apply(this, arguments);
}
/**
* Update Data
* @param {String} collectionName
* @param {FilterQuery<Object>} queryCondition
* @param {*} updateValue
* @param {ClientSession} session
* @return {UpdateWriteOpResult}
*/
function _insertOne() {
_insertOne = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee4(collectionName) {
var data,
session,
dbo,
resultObject,
_args4 = arguments;
return regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
data = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : {};
session = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : undefined;
_context4.prev = 2;
if (!(mongo === null || !mongo.isConnected())) {
_context4.next = 6;
break;
}
_context4.next = 6;
return openConnection();
case 6:
dbo = mongo.db(_config_db.default.DB_NAME);
_context4.next = 9;
return dbo.collection(collectionName).insertOne(data, {
session: session
});
case 9:
resultObject = _context4.sent;
_logger.default.db("Insert data to " + collectionName + " Success.");
return _context4.abrupt("return", resultObject);
case 14:
_context4.prev = 14;
_context4.t0 = _context4["catch"](2);
throw _context4.t0;
case 17:
case "end":
return _context4.stop();
}
}
}, _callee4, null, [[2, 14]]);
}));
return _insertOne.apply(this, arguments);
}
function updateOne(_x4) {
return _updateOne.apply(this, arguments);
}
/**
* Update Many Data
* @param {String} collectionName
* @param {*} queryCondition
* @param {*} updateValue
* @param {ClientSession} session
*/
function _updateOne() {
_updateOne = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee5(collectionName) {
var queryCondition,
updateValue,
session,
dbo,
resultObject,
_args5 = arguments;
return regeneratorRuntime.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
queryCondition = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {};
updateValue = _args5.length > 2 && _args5[2] !== undefined ? _args5[2] : {};
session = _args5.length > 3 && _args5[3] !== undefined ? _args5[3] : undefined;
_context5.prev = 3;
if (!(mongo === null || !mongo.isConnected())) {
_context5.next = 7;
break;
}
_context5.next = 7;
return openConnection();
case 7:
dbo = mongo.db(_config_db.default.DB_NAME);
_context5.next = 10;
return dbo.collection(collectionName).updateOne(queryCondition, updateValue, {
session: session
});
case 10:
resultObject = _context5.sent;
_logger.default.db("Update data to " + collectionName + " Success.");
return _context5.abrupt("return", resultObject);
case 15:
_context5.prev = 15;
_context5.t0 = _context5["catch"](3);
throw _context5.t0;
case 18:
case "end":
return _context5.stop();
}
}
}, _callee5, null, [[3, 15]]);
}));
return _updateOne.apply(this, arguments);
}
function updateMany(_x5) {
return _updateMany.apply(this, arguments);
}
/**
* Delete From
* @param {String} collectionName
* @param {*} queryCondition
* @param {ClientSession} session
* @return {DeleteWriteOpResultObject}
*/
function _updateMany() {
_updateMany = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee6(collectionName) {
var queryCondition,
updateValue,
session,
dbo,
resultObject,
_args6 = arguments;
return regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
queryCondition = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {};
updateValue = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : {};
session = _args6.length > 3 && _args6[3] !== undefined ? _args6[3] : undefined;
_context6.prev = 3;
if (!(mongo === null || !mongo.isConnected())) {
_context6.next = 7;
break;
}
_context6.next = 7;
return openConnection();
case 7:
dbo = mongo.db(_config_db.default.DB_NAME);
_context6.next = 10;
return dbo.collection(collectionName).updateMany(queryCondition, updateValue, {
session: session
});
case 10:
resultObject = _context6.sent;
_logger.default.db("Update data to " + collectionName + " Success.");
return _context6.abrupt("return", resultObject);
case 15:
_context6.prev = 15;
_context6.t0 = _context6["catch"](3);
throw _context6.t0;
case 18:
case "end":
return _context6.stop();
}
}
}, _callee6, null, [[3, 15]]);
}));
return _updateMany.apply(this, arguments);
}
function deleteMany(_x6, _x7) {
return _deleteMany.apply(this, arguments);
}
/**
* @description Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
* http://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#findOneAndUpdate
* @param {String} collectionName
* @param {FilterQuery<Object>} queryCondition
* @param {UpdateQuery<Object>} updateValue
* @param {ClientSession} session
*
* @returns {FindAndModifyWriteOpResultObject<Object>}
*/
function _deleteMany() {
_deleteMany = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee7(collectionName, queryCondition) {
var session,
dbo,
resultObject,
_args7 = arguments;
return regeneratorRuntime.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
session = _args7.length > 2 && _args7[2] !== undefined ? _args7[2] : undefined;
_context7.prev = 1;
if (!(mongo === null || !mongo.isConnected())) {
_context7.next = 5;
break;
}
_context7.next = 5;
return openConnection();
case 5:
dbo = mongo.db(_config_db.default.DB_NAME);
_context7.next = 8;
return dbo.collection(collectionName).deleteMany(queryCondition, {
session: session
});
case 8:
resultObject = _context7.sent;
_logger.default.db("Delete data from " + collectionName + " Success.");
return _context7.abrupt("return", resultObject);
case 13:
_context7.prev = 13;
_context7.t0 = _context7["catch"](1);
throw _context7.t0;
case 16:
case "end":
return _context7.stop();
}
}
}, _callee7, null, [[1, 13]]);
}));
return _deleteMany.apply(this, arguments);
}
function findOneAndUpdate(_x8) {
return _findOneAndUpdate.apply(this, arguments);
}
/**
* Select * From
* @param {String} collectionName
* @param {Object[]} pipeline
*/
function _findOneAndUpdate() {
_findOneAndUpdate = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee8(collectionName) {
var queryCondition,
updateValue,
session,
dbo,
resultObject,
_args8 = arguments;
return regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
queryCondition = _args8.length > 1 && _args8[1] !== undefined ? _args8[1] : {};
updateValue = _args8.length > 2 && _args8[2] !== undefined ? _args8[2] : {};
session = _args8.length > 3 && _args8[3] !== undefined ? _args8[3] : undefined;
_context8.prev = 3;
if (!(mongo === null || !mongo.isConnected())) {
_context8.next = 7;
break;
}
_context8.next = 7;
return openConnection();
case 7:
dbo = mongo.db(_config_db.default.DB_NAME);
_context8.next = 10;
return dbo.collection(collectionName).findOneAndUpdate(queryCondition, updateValue, {
session: session
});
case 10:
resultObject = _context8.sent;
_logger.default.db("Update data to " + collectionName + " Success.");
return _context8.abrupt("return", resultObject);
case 15:
_context8.prev = 15;
_context8.t0 = _context8["catch"](3);
throw _context8.t0;
case 18:
case "end":
return _context8.stop();
}
}
}, _callee8, null, [[3, 15]]);
}));
return _findOneAndUpdate.apply(this, arguments);
}
function aggregate(_x9) {
return _aggregate.apply(this, arguments);
}
/**
* @returns {ClientSession}
*/
function _aggregate() {
_aggregate = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee9(collectionName) {
var pipeline,
dbo,
resultObject,
_args9 = arguments;
return regeneratorRuntime.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
pipeline = _args9.length > 1 && _args9[1] !== undefined ? _args9[1] : {};
_context9.prev = 1;
if (!(mongo === null || !mongo.isConnected())) {
_context9.next = 5;
break;
}
_context9.next = 5;
return openConnection();
case 5:
dbo = mongo.db(_config_db.default.DB_NAME);
_context9.next = 8;
return dbo.collection(collectionName).aggregate(pipeline).toArray();
case 8:
resultObject = _context9.sent;
_logger.default.db("Find data from " + collectionName + " Success.");
return _context9.abrupt("return", resultObject);
case 13:
_context9.prev = 13;
_context9.t0 = _context9["catch"](1);
throw _context9.t0;
case 16:
case "end":
return _context9.stop();
}
}
}, _callee9, null, [[1, 13]]);
}));
return _aggregate.apply(this, arguments);
}
function CreateSession() {
return _CreateSession.apply(this, arguments);
}
function _CreateSession() {
_CreateSession = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee10() {
var sessions;
return regeneratorRuntime.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
_context10.prev = 0;
if (!(mongo === null || !mongo.isConnected())) {
_context10.next = 4;
break;
}
_context10.next = 4;
return openConnection();
case 4:
sessions = mongo.startSession({
defaultTransactionOptions: {
readConcern: {
level: 'local'
},
writeConcern: {
w: 'majority'
},
readPreference: 'primary'
}
});
return _context10.abrupt("return", sessions);
case 8:
_context10.prev = 8;
_context10.t0 = _context10["catch"](0);
throw _context10.t0;
case 11:
case "end":
return _context10.stop();
}
}
}, _callee10, null, [[0, 8]]);
}));
return _CreateSession.apply(this, arguments);
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _app_config = _interopRequireDefault(require("../../../config/app_config"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Config Database
var DB_USERNAME = encodeURIComponent(_app_config.default.systemConfig.DB_USERNAME);
var DB_PASSWORD = encodeURIComponent(_app_config.default.systemConfig.DB_PASSWORD);
var DB_NAME = _app_config.default.systemConfig.DB_NAME;
var DB_PORT = _app_config.default.systemConfig.DB_PORT;
var DB_URL = _app_config.default.systemConfig.DB_URL;
var DB_CONNECT_STR = "mongodb://".concat(DB_USERNAME, ":").concat(DB_PASSWORD, "@").concat(DB_URL, ":").concat(DB_PORT, "/").concat(DB_NAME);
var _default = {
DB_CONNECT_STR: DB_CONNECT_STR,
DB_NAME: DB_NAME
};
exports.default = _default;
\ No newline at end of file
...@@ -22,6 +22,8 @@ ...@@ -22,6 +22,8 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"dotenv": "^8.2.0" "dotenv": "^8.2.0",
"moment": "2.29.1",
"mongodb": "3.1.8"
} }
} }
import dotenv from 'dotenv' import dotenv from 'dotenv'
import ConnectMongo from './utils/mongodb/connect_db';
dotenv.config(); dotenv.config();
export class Utils { export class Utils {
...@@ -17,4 +18,6 @@ export class Utils { ...@@ -17,4 +18,6 @@ export class Utils {
export const ENV = { export const ENV = {
env : process.env env : process.env
} }
\ No newline at end of file
export const connectMongo = new ConnectMongo();
\ No newline at end of file
import moment from "moment";
export default {
log: (...args) => {
const req = args[0];
if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log(`\x1b[0m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
},
info: (...args) => {
const req = args[0];
if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log(`\x1b[36m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
},
error: (...args) => {
const req = args[0];
if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log(`\x1b[31m${getTime()} ERROR ${toString(args).join('')}\x1b[0m`)
},
warning: (...args) => {
const req = args[0];
if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log(`\x1b[33m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
},
success: (...args) => {
const req = args[0];
if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log(`\x1b[32m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
},
magenta: (...args) => {
const req = args[0];
if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log(`\x1b[35m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
},
random: (...args) => {
const req = args[0];
if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log((toString(args).join('').split('').map(item => '\x1b[' + randomColor() + 'm' + item + '\x1b[0m')).join('') + '\n')
},
db: (...args) => {
const req = args[0];
if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
args[0] = req.headers.__reqId;
}
console.log(`\x1b[35m${getTime()} INFO [Database Message] ${toString(args).join('')}\x1b[0m`)
},
}
/**
* Random color not duplicate next character
*/
let tempColor = null;
let randomColor = () => {
if (tempColor != null) {
const rand = Math.floor(Math.random() * (37 - 31) + 31);
if (rand != tempColor) {
tempColor = rand;
return rand;
} else {
return randomColor();
}
} else {
tempColor = Math.floor(Math.random() * (37 - 31) + 31);
return tempColor;
}
}
let toString = (list) => {
return list.map(item => item.constructor.name == 'Object' || item.constructor.name == 'Array' ? JSON.stringify(item) : item);
}
let getTime = () => moment().format("YYYY-MM-DD HH:mm:ss:SSS");
\ No newline at end of file
export default {
DMA5_DMA_OBJECT : "dma5_dma_object",
DMA5_CONFIG: "dma5_config",
DMA5_BUILDER_ENV: "dma5_builder_env",
DMA5_PUBLISH_QUEUE: "dma5_publish_queue",
DMA5_CARD_PROTOTYPE: "dma5_card_prototype",
DMA_SCREEN : "app_ui_config",
DMA_STORYBOARD : "story_board_config",
DMA_STORYBOARD_LIST : "storyboard_storyboardlist",
DMA_STORYBOARD_GROUP : "storyboard_groups",
DMA_MASTER_NATIVE_INPUT : 'screen_native_input_type'
}
\ No newline at end of file
import COLLECTION from "./collections";
import * as dbActions from "./db_config/action";
class ConnectMongo {
constructor(){
dbActions.openConnection();
}
}
export default ConnectMongo;
\ No newline at end of file
import { MongoClient, FilterQuery, UpdateQuery, FindAndModifyWriteOpResultObject, OptionalId, ClientSession ,DeleteWriteOpResultObject ,UpdateWriteOpResult} from 'mongodb';
import config from "./config_db";
import logger from "../../logger/logger";
import appConfig from "../../../config/app_config";
/**
* @type {MongoClient}
*/
var mongo = null;
const TAG = "[ConnectMongo] "
async function openConnection() {
try {
mongo = await MongoClient.connect(config.DB_CONNECT_STR, {
useNewUrlParser: true,
useUnifiedTopology: true,
poolSize: appConfig.config.db_connection_pool_size
});
logger.info(`${TAG}::::::::::::::: Mongo DB is connected ::::::::::::::::`);
} catch (error) {
logger.error(`${TAG}::::::::::::::: Cannot connect to Mongo DB ::::::::::::::::\n${error}`);
}
}
/**
* Select * From
* @param {String} collectionName
* @param {*} queryCondition
* @param {Object} filter
* @returns {Promise<Array>}
*/
async function find(collectionName, queryCondition = {}, filter = {}) {
try {
if (mongo === null || !mongo.isConnected()) await openConnection();
const dbo = mongo.db(config.DB_NAME);
const resultObject = await dbo.collection(collectionName)
.find(queryCondition, { projection: { ...filter } })
.toArray();
logger.db("Find data from " + collectionName + " Success.");
return resultObject;
} catch (error) {
// logger.error("Find data from " + collectionName + " Failed.");
// logger.error("Error : ", error);
throw error;
}
}
/**
* Select * From Where Only One Data
* @param {String} collectionName
* @param {*} queryCondition
*/
async function findOne(collectionName, queryCondition = {}) {
try {
if (mongo === null || !mongo.isConnected()) await openConnection();
const dbo = mongo.db(config.DB_NAME);
const resultObject = await dbo.collection(collectionName)
.findOne(queryCondition, { projection: { _id: 0 } })
logger.db("Find data from " + collectionName + " Success.");
return resultObject;
} catch (error) {
// logger.error("Find data from " + collectionName + " Failed.");
// logger.error("Error : ", error);
throw error;
}
}
/**
* Insert One Data
* @param {String} collectionName
* @param {OptionalId<Object>} data
* @param {ClientSession} session
*/
async function insertOne(collectionName, data = {}, session = undefined) {
try {
if (mongo === null || !mongo.isConnected()) await openConnection();
const dbo = mongo.db(config.DB_NAME);
const resultObject = await dbo.collection(collectionName).insertOne(data, {session});
logger.db("Insert data to " + collectionName + " Success.");
return resultObject;
} catch (error) {
// logger.error("Insert data to " + collectionName + " Failed.");
// logger.error("Error : ", error);
throw error;
}
}
/**
* Update Data
* @param {String} collectionName
* @param {FilterQuery<Object>} queryCondition
* @param {*} updateValue
* @param {ClientSession} session
* @return {UpdateWriteOpResult}
*/
async function updateOne(collectionName, queryCondition = {}, updateValue = {}, session = undefined) {
try {
if (mongo === null || !mongo.isConnected()) await openConnection();
const dbo = mongo.db(config.DB_NAME);
const resultObject = await dbo.collection(collectionName).updateOne(queryCondition, updateValue, {session});
logger.db("Update data to " + collectionName + " Success.");
return resultObject;
} catch (error) {
// logger.error("Update data to " + collectionName + " Failed.");
// logger.error("Error : ", error);
throw error;
}
}
/**
* Update Many Data
* @param {String} collectionName
* @param {*} queryCondition
* @param {*} updateValue
* @param {ClientSession} session
*/
async function updateMany(collectionName, queryCondition = {}, updateValue = {}, session = undefined) {
try {
if (mongo === null || !mongo.isConnected()) await openConnection();
const dbo = mongo.db(config.DB_NAME);
const resultObject = await dbo.collection(collectionName).updateMany(queryCondition, updateValue, {session});
logger.db("Update data to " + collectionName + " Success.");
return resultObject;
} catch (error) {
// logger.error("Update data to " + collectionName + " Failed.");
// logger.error("Error : ", error);
throw error;
}
}
/**
* Delete From
* @param {String} collectionName
* @param {*} queryCondition
* @param {ClientSession} session
* @return {DeleteWriteOpResultObject}
*/
async function deleteMany(collectionName, queryCondition, session = undefined) {
try {
if (mongo === null || !mongo.isConnected()) await openConnection();
const dbo = mongo.db(config.DB_NAME);
const resultObject = await dbo.collection(collectionName).deleteMany(queryCondition, {session});
logger.db("Delete data from " + collectionName + " Success.");
return resultObject;
} catch (error) {
// logger.error("Delete data from " + collectionName + " Failed.");
// logger.error("Error : ", error);
throw error;
}
}
/**
* @description Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
* http://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#findOneAndUpdate
* @param {String} collectionName
* @param {FilterQuery<Object>} queryCondition
* @param {UpdateQuery<Object>} updateValue
* @param {ClientSession} session
*
* @returns {FindAndModifyWriteOpResultObject<Object>}
*/
async function findOneAndUpdate(collectionName, queryCondition = {}, updateValue = {}, session = undefined) {
try {
if (mongo === null || !mongo.isConnected()) await openConnection();
const dbo = mongo.db(config.DB_NAME);
const resultObject = await dbo.collection(collectionName).findOneAndUpdate(queryCondition, updateValue, {session})
logger.db("Update data to " + collectionName + " Success.");
return resultObject;
} catch (error) {
// logger.error("Update data to " + collectionName + " Failed.");
// logger.error("Error : ", error);
throw error;
}
}
/**
* Select * From
* @param {String} collectionName
* @param {Object[]} pipeline
*/
async function aggregate(collectionName, pipeline = {}) {
try {
if (mongo === null || !mongo.isConnected()) await openConnection();
const dbo = mongo.db(config.DB_NAME);
const resultObject = await dbo.collection(collectionName)
.aggregate(pipeline)
.toArray();
logger.db("Find data from " + collectionName + " Success.");
return resultObject;
} catch (error) {
// logger.error("Find data from " + collectionName + " Failed.");
// logger.error("Error : ", error);
throw error;
}
}
/**
* @returns {ClientSession}
*/
async function CreateSession() {
try {
if (mongo === null || !mongo.isConnected()) await openConnection();
const sessions = mongo.startSession({
defaultTransactionOptions: {
readConcern: { level: 'local' },
writeConcern: { w: 'majority' },
readPreference: 'primary'
}
});
return sessions
} catch (error) {
// logger.error("Find data from " + collectionName + " Failed.");
// logger.error("Error : ", error);
throw error;
}
}
export {
openConnection,
find,
findOne,
insertOne,
updateOne,
updateMany,
deleteMany,
findOneAndUpdate,
aggregate,
CreateSession
}
\ No newline at end of file
import appConfig from "../../../config/app_config";
// Config Database
const DB_USERNAME = encodeURIComponent(appConfig.systemConfig.DB_USERNAME);
const DB_PASSWORD = encodeURIComponent(appConfig.systemConfig.DB_PASSWORD);
const DB_NAME = appConfig.systemConfig.DB_NAME;
const DB_PORT = appConfig.systemConfig.DB_PORT;
const DB_URL = appConfig.systemConfig.DB_URL;
const DB_CONNECT_STR = `mongodb://${DB_USERNAME}:${DB_PASSWORD}@${DB_URL}:${DB_PORT}/${DB_NAME}`;
export default {
DB_CONNECT_STR : DB_CONNECT_STR,
DB_NAME : DB_NAME,
}
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!