zync-nest-library
Version:
NestJS library with database backup and file upload utilities
188 lines (165 loc) • 5.38 kB
text/typescript
var randomize = require("randomatic");
import * as bcrypt from "bcryptjs";
import * as _ from "lodash";
var randomize = require("randomatic");
const http = require("http"),
https = require("https");
var Stream = require("stream").Transform;
export interface INode {
_id: string;
children?: any;
[x: string]: string | INode[];
}
export const helper = {
removeSpecialChar: (val: string) => {
return val?.replace(/[^a-zA-Z0-9 ]/g, "");
},
replaceAll: (find, replace, str) => {
return str.replace(new RegExp(find, "g"), replace);
},
randomDigits: (length = 6) => {
return randomize("0", length);
},
hash: async (password: string, salt: number = 10): Promise<string> => {
return await bcrypt.hash(password, salt);
},
base64Encode: (str: string) => {
return btoa(unescape(encodeURIComponent(str)));
},
downloadImageFromURL: (url) => {
return new Promise((resolve, reject) => {
var client = http;
if (url.toString().indexOf("https") === 0) {
client = https;
}
client
.request(url, function (response) {
var data = new Stream();
response.on("data", function (chunk) {
data.push(chunk);
});
response.on("end", function () {
// fs.writeFileSync(filename, data.read());
resolve(data.read());
});
})
.end();
});
},
getHostName: (url: string) =>
url ? url?.toString().replace(/^(.*\/\/[^\/?#]*).*$/, "$1") : "",
isValidURL: (input: string) => {
const pattern =
"^(https?:\\/\\/)?" + // protocol
"((([a-zA-Z\\d]([a-zA-Z\\d-]{0,61}[a-zA-Z\\d])*\\.)+" + // sub-domain + domain name
"[a-zA-Z]{2,13})" + // extension
"|((\\d{1,3}\\.){3}\\d{1,3})" + // OR ip (v4) address
"|localhost)" + // OR localhost
"(\\:\\d{1,5})?" + // port
"(\\/[a-zA-Z\\&\\d%_.~+-:@]*)*" + // path
"(\\?[a-zA-Z\\&\\d%_.,~+-:@=;&]*)?" + // query string
"(\\#[-a-zA-Z&\\d_]*)?$"; // fragment locator
const regex = new RegExp(pattern);
return regex.test(input);
},
groupArrayObj: (key: string, array: Array<any>): Array<any> => {
return _(array)
.groupBy(key)
.map((items, ky) => {
return { key: ky, items };
})
.value();
},
formatAmt: (amt: number | string, precision = 2) => {
if (typeof amt !== "number" && typeof amt !== "string") {
return parseFloat("0.00");
}
let amtFloat = parseFloat(amt as any);
if (isNaN(amtFloat)) {
return parseFloat("0.00");
}
let sciNotation = amtFloat.toPrecision(precision);
let regularNotation = parseFloat(sciNotation).toString();
// If the regular notation ends with '.0', remove that part.
if (regularNotation.endsWith(".0")) {
regularNotation = regularNotation.slice(0, -2);
}
// Truncate to 2 decimal places without rounding
let truncatedAmt = Math.floor(amtFloat * 100) / 100;
return parseFloat(truncatedAmt.toFixed(2));
},
toQueryString: (obj: Object) => {
const keyValuePairs = [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
// If the value is an array, repeat the key for each element
if (Array.isArray(value)) {
value.forEach((element) => {
keyValuePairs.push(
`${encodeURIComponent(key)}=${encodeURIComponent(element)}`
);
});
} else {
keyValuePairs.push(
`${encodeURIComponent(key)}=${encodeURIComponent(value)}`
);
}
}
}
return keyValuePairs.join("&");
},
convertObjectToUnderscoredString(obj) {
// Convert the keys from camelCase to underscored
const underscoredObject = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const underscoredKey = key
.replace(/([A-Z])/g, "_$1")
.toLowerCase()
.replace(/:/g, "_");
underscoredObject[underscoredKey] = obj[key];
}
}
// Remove double quotes from the string
return JSON.stringify(underscoredObject)
.slice(1, -1)
.replace(/:/g, "_")
.replace(/,/g, "_")
.replace(/[^\w_]/g, "");
},
generateInitials(str: string) {
// Split the name into words
const words = str.split(" ");
// Initialize an empty string to store initials
let initials = "";
// Iterate through the words and add the first letter of each word to the initials
for (let i = 0; i < words.length; i++) {
const word = words[i];
if (word.length > 0) {
initials += word[0].toUpperCase();
}
}
return initials;
},
mapNode(nodes: INode[]): INode[] {
const nodeMap: Map<string, INode> = new Map();
const mappedNodes: INode[] = [];
// Populate the map with nodes
nodes.forEach((node) => {
nodeMap.set(node._id.toString(), { ...node, children: [] });
});
// Assign children to their respective parents
nodes.forEach((node) => {
if (node.parentId) {
const parent = nodeMap.get(node.parentId.toString());
if (parent) {
parent.children.push(nodeMap.get(node._id.toString()));
}
} else {
mappedNodes.push(nodeMap.get(node._id.toString()));
}
});
return mappedNodes;
},
};