gb_utils
Version:
All utils file for beta
160 lines (144 loc) • 4.61 kB
JavaScript
// Dependencies Import
const mongoose = require("mongoose");
const CryptoJS = require("crypto-js");
const fs = require('fs');
const path = require('path');
const constantUtils = require('./constantUtils');
const utils = {};
// Normalize a port into a number, string, or false.
utils.normalizePort = (data) => {
const port = parseInt(data, 10);
if (isNaN(port)) {
// named pipe
return data;
}
if (port >= 0) {
// port number
return port;
}
return false;
};
// change normal stringId into MongoId
utils.getMongoIds = async (data) => {
return data.map((e) => new mongoose.Types.ObjectId(e));
};
// To generate Random string
utils.randomString = async (data) => {
let mask = "";
if (data.type.indexOf("a") > -1) mask += "abcdefghijklmnopqrstuvwxyz";
if (data.type.indexOf("A") > -1) mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (data.type.indexOf("#") > -1) mask += "123456789";
let result = "";
for (let i = data.length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
return result;
};
// create logfile name in dataformat
utils.getFileDateGenerator = async (data) => {
const pad = (num) => (num > 9 ? "" : "0") + num;
const time = new Date();
const month = time.getFullYear() + "" + pad(time.getMonth() + 1);
const day = pad(time.getDate());
const year = pad(time.getFullYear());
return `${year}${month}${day}${data}-file.log`;
};
// Get hostIp based on network
utils.getHostIp = (data) => {
let ip = "localhost";
const arr = data["Wi-Fi"] ? data["Wi-Fi"] : data["Wi-Fi 2"];
arr.map((e) => {
if (e.family === "IPv4") ip = e.address;
});
return ip;
};
// Encrypting the response data
utils.dataEncryption = (dataObj) => {
const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(dataObj), dataObj.config.SECRECTENCRYPECODE).toString();
return ciphertext;
};
// Encrypting the response data
utils.getRandomDate = () => {
const maxDate = Date.now();
const timestamp = Math.floor(Math.random() * maxDate);
return new Date(timestamp);
};
// Add Device Info
utils.checkDeviceInfo = (req, token, deviceInfos) => {
let infoType = false;
if (deviceInfos.length > 0) {
deviceInfos.map((e) => {
if (e.deviceId === req.headers.deviceid) {
infoType = true;
e.accessToken = token;
e.userAgent = req.headers["user-agent"];
e.deviceId = req.headers.deviceid;
e.ip = req.headers.ip;
e.deviceType = req.headers.devicetype;
e.platform = req.headers.platform;
return e;
} else {
return e;
}
});
}
if (!infoType) {
deviceInfos.push({
accessToken: token,
userAgent: req.headers["user-agent"],
deviceId: req.headers.deviceid,
ip: req.headers.ip,
deviceType: req.headers.devicetype,
platform: req.headers.platform,
});
}
return deviceInfos;
};
// Get Current Device Info
utils.getCurrentDeviceInfo = (req, deviceInfos) => {
if (deviceInfos.length > 0) {
deviceInfos.filter((e) => e.deviceId === req.headers.deviceid);
}
return deviceInfos;
};
// Get notification Payload
utils.getNoificationPayload = (req, receiverId, uniqueCode, notificationText, type) => {
const link = `/${type === 'follow' ? 'profile' : type === 'comment' ? 'post' : 'post'}/${uniqueCode}`;
const params = {
"type": type === 'post' ? constantUtils.LIKE : type === 'follow' ? constantUtils.FOLLOW : type === 'comment' ? constantUtils.COMMENT : constantUtils.POSTSHARED,
"sender": {
"_id": req.user._id,
"uniqueCode": req.user.uniqueCode,
"userName": req.user.userName,
"avatar": req.user.avatar,
"userBio": req.user.userBio,
"profilePic": req.user.profilePic,
"coverPic": req.user.coverPic
},
"receiver": receiverId,
"postId": req.body.postId || null,
"commentId": req.body.commentId || null,
"likeType": req.body.likeType || null,
"text": notificationText,
"link": link,
"isRead": false,
"status": constantUtils.ACTIVE
};
return params;
};
utils.updateJsArrayFile = (filePath, newItem, uniqueKey = 'url') => {
try {
delete require.cache[require.resolve(filePath)];
const dataArray = require(filePath);
const exists = dataArray.find(item => item[uniqueKey] === newItem[uniqueKey]);
if (exists) {
console.log(`[SKIP] ${newItem[uniqueKey]} already exists in ${path.basename(filePath)}`);
return;
}
dataArray.push(newItem);
const fileContent = `module.exports = ${JSON.stringify(dataArray, null, 2)};\n`;
fs.writeFileSync(filePath, fileContent, 'utf8');
console.log(`[UPDATE] Added ${newItem[uniqueKey]} to ${path.basename(filePath)}`);
} catch (err) {
console.error(`[ERROR] Failed to update ${filePath}:`, err);
}
};
module.exports = utils;