Skip to content

Commit

Permalink
fix bd init
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander authored and Alexander committed Nov 27, 2022
1 parent 0a22deb commit cfb95bb
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 19 deletions.
8 changes: 4 additions & 4 deletions my-server/controllers/products.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const path = require("path");
const { ObjectId } = require("mongodb");
const { initConfLog, initMongoDb, codes } = require("server-framework");
const { initConfLog, getDbWithCollectionInit, codes } = require("server-framework");

const configPath = path.join(__dirname, "configs", "config.json");

Expand All @@ -10,8 +10,8 @@ const getId = async (req, res) => {
const { logger, config } = initConfLog(configPath);
const collName = config.get("dbConfig").collName;

const db = await initMongoDb();
const db = await getDbWithCollectionInit();

const dbResponse = await db
.collection(collName)
.findOne({ _id: new ObjectId(req.params.id) });
Expand All @@ -38,7 +38,7 @@ const create = async (req, res) => {
const { logger, config } = initConfLog(configPath);
const collName = config.get("dbConfig").collName;

const db = await initMongoDb();
const db = await getDbWithCollectionInit();

const data = req.body;
logger.info("data", data);
Expand Down
6 changes: 3 additions & 3 deletions my-server/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const fs = require("fs");
const path = require("path");

const { server, initConfLog, codes } = require("server-framework");
const { server, initConfLog, initMongoDb, codes } = require("server-framework");

const protectedMiddleware = require("./middlewares/protectedMiddleware");
const productRoutes = require("./routes/products");
Expand All @@ -11,11 +11,11 @@ const configPath = path.join(__dirname, "configs", "config.json");
const logsFolderPath = path.join(__dirname, "logs");

const start = async () => {

const { logger, config } = initConfLog(configPath, logsFolderPath);
const appPort = config.get("appPort");

await initMongoDb();
const app = server();

app.addContentTypeParser("application/json", defaultJsonParser);

const router = app.Router;
Expand Down
31 changes: 20 additions & 11 deletions server-framework/ServerGlobal.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ const nconf = require("nconf");
class ServerGlobal {
_config;
_logger;
_dbConnection;

static _instance;

constructor(configPathname, logsFolderPath) {
console.log("path", configPathname);
this._config = nconf.argv().env().file({ file: configPathname });


const { errorFile, combinedFile, env } = this._config.get("logger");

if (!fs.existsSync(logsFolderPath)) {
Expand Down Expand Up @@ -44,32 +44,38 @@ class ServerGlobal {
}

async initMongo() {
const { mongoUrl, dbName, collName, validatorObj } =
this._config.get("dbConfig");
const { mongoUrl, dbName } = this._config.get("dbConfig");
const client = new MongoClient(mongoUrl);

this._logger.info("initDb");
try {
await client.connect();
this._logger.info("Connected successfully to server");
const db = client.db(dbName);
this._dbConnection = client.db(dbName);
} catch (e) {
this._logger.error(`Error init database collection ${e}`);
}
}

async getDbWithCollectionInit() {
const { collName, validatorObj } = this._config.get("dbConfig");

const collection = await client
.db(dbName)
try {
const collection = await this._dbConnection
.listCollections({}, { nameOnly: true })
.toArray();

if (
collection.filter((collectionItem) => collectionItem.name === collName)
.length
) {
return db;
return this._dbConnection;
} else {
await db.createCollection(collName, validatorObj);
return db;
await this._dbConnection.createCollection(collName, validatorObj);
return this._dbConnection;
}
} catch (e) {
this._logger.error(`Error init database collection ${e}`);
this._logger.error(`Error collection create ${e}`);
}
}

Expand All @@ -89,7 +95,10 @@ class ServerGlobal {
get logger() {
return this._logger;
}
}

get db() {
return this._dbConnection;
}
}

module.exports = ServerGlobal;
3 changes: 2 additions & 1 deletion server-framework/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const ServerGlobal = require("./ServerGlobal");

const initConfLog = (path, logsPath) => ServerGlobal.getInstance(path, logsPath);
const initMongoDb = () => ServerGlobal.getInstance().initMongo()
const getDbWithCollectionInit = () => ServerGlobal.getInstance().getDbWithCollectionInit()

function createResponse(res) {
res.send = (message) => res.end(message);
Expand Down Expand Up @@ -159,4 +160,4 @@ function customServer() {
};
}

module.exports = { server: customServer, initConfLog, initMongoDb, codes };
module.exports = { server: customServer, initConfLog, initMongoDb, getDbWithCollectionInit, codes };

0 comments on commit cfb95bb

Please sign in to comment.