Skip to content

Commit

Permalink
🚀 Miscellaneous Refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
Muhammad Owais committed Jan 4, 2024
1 parent 36c8a7f commit f02bd20
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 95 deletions.
9 changes: 6 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// require node version>=14.0 to run the app,
// because we use optional chaining etc...
const express = require('express');
const injectMiddleWares = require('./src/middleware');
const errorMiddleware = require('./src/middleware/error');
Expand All @@ -8,6 +6,9 @@ const routes = require('./src/routes');
const { validateEnvVar, loadDataInMemory } = require('./src/utils/util');
const { version } = require('./package.json');

// use database to store logs and custom responses
require('./src/db/mongoose');

const { PORT = 3000, NODE_ENV } = process.env;

// validate if we have all the env variables setup.
Expand Down Expand Up @@ -47,5 +48,7 @@ app.use(errorMiddleware);

// start listening
app.listen(PORT, () => {
console.info(`[Node][${NODE_ENV}] App v${version} running on PORT ${PORT}`);
console.info(
`[Node][${NODE_ENV}] App v${version} running at http://localhost:${PORT}`,
);
});
24 changes: 16 additions & 8 deletions src/db/mongoose.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
const mongoose = require('mongoose');
const { isDbConnected, updatedDbConnectionStatus } = require('../utils/db');

const { MONGODB_URI, MONGODB_DB_NAME } = process.env;

mongoose
.connect(MONGODB_URI, {
connectDB();

async function connectDB() {
if (!MONGODB_URI || isDbConnected()) return;
const dbOptions = {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: MONGODB_DB_NAME || 'logs',
})
.then(() => {
};

try {
await mongoose.connect(MONGODB_URI, dbOptions);
updatedDbConnectionStatus(true);
console.info('[Service:Database] Connected.');
})
.catch(err => {
} catch (err) {
updatedDbConnectionStatus(false);
console.error('[Service:Database] Err: Failed to Connect.', err);

process.exit(1);
});
}
}

// If mongoose gets disconnected, show this message
mongoose.connection.on('disconnected', () => {
updatedDbConnectionStatus(false);
console.info('[Service:Database] Disconnected.');

// [optional] exit app when database is disconnected
Expand Down
10 changes: 2 additions & 8 deletions src/middleware/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,7 @@ const onFinished = require('on-finished');
const onHeaders = require('on-headers');
const Log = require('../models/log');
const { isRequestInWhitelist } = require('../helpers');

// use database to store logs
const { MONGODB_URI } = process.env;

if (MONGODB_URI) {
require('../db/mongoose');
}
const { isDbConnected } = require('../utils/db');

let count = 0;
startCountLogger();
Expand Down Expand Up @@ -56,7 +50,7 @@ function logger(req, res, next) {
totalTimeMS: getTotalTime(req, res),
});

if (MONGODB_URI) {
if (isDbConnected()) {
log.save(err => {
if (err) {
console.log({ logError: err.message });
Expand Down
9 changes: 9 additions & 0 deletions src/utils/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const util = {};

let _isDbConnected = false;

util.isDbConnected = () => _isDbConnected;

util.updatedDbConnectionStatus = bool => (_isDbConnected = bool);

module.exports = util;
8 changes: 4 additions & 4 deletions src/utils/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ const jwt = require('jsonwebtoken');

const { JWT_SECRET } = process.env;

const controller = {};
const util = {};

controller.generateToken = (payload, expiresInMins) => {
util.generateToken = (payload, expiresInMins) => {
return new Promise((resolve, reject) => {
let expiresIn = '60m';

Expand All @@ -21,7 +21,7 @@ controller.generateToken = (payload, expiresInMins) => {
});
};

controller.verifyToken = Authorization => {
util.verifyToken = Authorization => {
return new Promise((resolve, reject) => {
const token = Authorization.replace('Bearer ', '');
jwt.verify(token, JWT_SECRET, (err, decoded) => {
Expand All @@ -35,4 +35,4 @@ controller.verifyToken = Authorization => {
});
};

module.exports = controller;
module.exports = util;
72 changes: 0 additions & 72 deletions src/utils/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,39 +26,6 @@ utils.dataInMemory = data;

utils.isDev = process.env.NODE_ENV !== 'production';

utils.doTheHeck = async () => {
const shouldDoAnything = false;
if (!shouldDoAnything) return;

const theUser = path.join(__dirname, '../', 'data', 'users.json');

const [theUserString] = await Promise.all([fs.readFile(theUser, 'utf-8')]);

const theUserData = JSON.parse(theUserString);

const users = theUserData.map(u => ({
id: u.id,
firstName: u.firstName,
lastName: u.lastName,
maidenName: u.maidenName,
age: utils.getRandomInt(18, 50),
...u,
}));

await fs.writeFile(
path.join(__dirname, '../', 'data', `users-updated.json`),
JSON.stringify(users),
);

return null;
};

utils.getRandomInt = (min = 0, max = 100) => {
const _min = Math.ceil(min);
const _max = Math.floor(max);
return Math.floor(Math.random() * (_max - _min + 1)) + _min;
};

utils.loadDataInMemory = async () => {
const baseDir = path.join(__dirname, '../', 'data');

Expand Down Expand Up @@ -117,8 +84,6 @@ utils.getMultiObjectSubset = function(arr, keys) {
return arr.map(p => utils.getObjectSubset(p, keys));
};

utils.usernameRegex = /^[a-zA-Z0-9]*$/;

utils.isNumber = num => !Number.isNaN(Number(num));

utils.validateEnvVar = () => {
Expand Down Expand Up @@ -150,43 +115,6 @@ utils.trueTypeOf = obj => {
.toLowerCase();
};

utils.getRandomElementsFromArray = (arr, numberOfElementsRequired) => {
let n = numberOfElementsRequired;
let len = arr.length;

const result = new Array(n);
const taken = new Array(len);

if (n > len) {
throw new RangeError(
'getRandomElementsFromArray: more elements taken than available',
);
}

while (n--) {
const randomIdx = Math.floor(Math.random() * len);
result[n] = arr[randomIdx in taken ? taken[randomIdx] : randomIdx];
taken[randomIdx] = --len in taken ? taken[len] : len;
}
return result;
};

utils.mongooseOptions = {
regexFinder: something => ({ $options: 'i', $regex: something }),
updateMerge: { new: true, setDefaultsOnInsert: true, upsert: true },
};

utils.truncateString = (string = '', length = 30) => {
if (string.length <= length + 3) return string;

return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};

utils.truncateStringMiddle = (string, length = 30, start = 10, end = 10) => {
if (string.length < length) return string;
return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};

utils.deepFreeze = function(obj) {
Object.freeze(obj);

Expand Down

0 comments on commit f02bd20

Please sign in to comment.