Viewing File: /home/ubuntu/efiexchange-node-base/src/helpers/common.helper.ts

import config from "config";
import jwt from "jsonwebtoken";
import axios from "axios";
import crypto from "crypto";
import Web3 from "web3";
import { v4 as uuidv4 } from "uuid";
import { promises as fsPromises } from "fs";
import * as path from "path";
const FCM = require("fcm-node");

export function generateCardNumber(n: any) {
  return Math.random().toFixed(n).split(".")[1];
}

export function generatePaymentId() {
  return uuidv4();
}

export function formattedAmount(amount: any) {
  return amount + " " + config.get<string>("coinSymbol");
}

export function formattedBalance(amount: any, currency: any) {
  return amount + " " + currency;
}

export function generateCommonJwtToken(data: any) {
  const token = jwt.sign(data, config.get<string>("JWT_TOKEN_KEY"), {
    expiresIn: "1000h",
  });
  return token;
}

export function generateCardExpiry() {
  return randomIntFromInterval(1, 12) + "/" + randomIntFromInterval(22, 40);
}

export function randomIntFromInterval(min = 1, max = 12) {
  // min and max included
  return Math.floor(Math.random() * (max - min + 1) + min);
}

export function generateJwtToken(xwallet_id: any, wallet_address: any) {
  const token = jwt.sign(
    { xwallet_id: xwallet_id, wallet_address: wallet_address },
    config.get<string>("JWT_TOKEN_KEY"),
    {
      expiresIn: "100h",
    }
  );
  return token;
}

export function isEmpty(object: any) {
  return Object.keys(object).length === 0 ? true : false;
}
export function formatCardNumber(number: any) {
  let formatted = number ? number.match(/.{1,4}/g) : "";
  return formatted ? formatted.join(" ") : "";
}

export async function bscscanApi(url: any, method: any, data: any) {
  axios
    .request({
      method: "GET",
      url: url,
    })
    .then(function (response) {
      return response.data;
    })
    .catch(function (error) {
      return error.message;
    });
}

export function sendFcmNotification(device_token: any, data: any) {
  let serverKey =
    "AAAAvvnTu9s:APA91bHz-oQ-6cisR4vATP1Tiyg-2e-ExMg30C7lPkZ1DeoDEb4ceqo-cBb-lhLH_gEcG1PoPdmi60FOKhsTX8gpt6IHXS2XH5OxBjsAuzCzJ7Nkp6boQzqzFI3PFmiA-wFi4vNWtDU_";
  let fcm = new FCM(serverKey);
  let message = {
    //this may vary according to the message type (single recipient, multicast, topic, et cetera)
    to: device_token,
    collapse_key: "xpay",
    notification: {
      title: data.title,
      body: data.description,
    },
    data: data,
  };

  fcm.send(message, function (err: any, response: any) {
    if (err) {
      console.log("Something has gone wrong!", response);
    } else {
      console.log("Successfully sent", response);
    }
  });
}

export function customEncodeString(plaintext: any) {
  // const iv = crypto.randomBytes(16);
  const xpaySecretKey = config.get<string>("xpaySecretKey");
  const iv = xpaySecretKey.slice(xpaySecretKey.length - 10) + "123456";
  const cipher = crypto.createCipheriv(
    config.get<string>("encryptAlgorithm"),
    xpaySecretKey,
    iv
  );
  const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);

  // return {
  //   iv: iv.toString("hex"),
  //   content: encrypted.toString("hex"),
  // };

  return encrypted.toString("hex");
}

export function decodeString(hash: any) {
  const decipher = crypto.createDecipheriv(
    config.get<string>("encryptAlgorithm"),
    config.get<string>("xpaySecretKey"),
    Buffer.from(hash.iv, "hex")
  );

  const decrpyted = Buffer.concat([
    decipher.update(Buffer.from(hash.content, "hex")),
    decipher.final(),
  ]);

  return decrpyted.toString();
}

export function transStatusText(status: any) {
  console.log("transStatusText", status);
  let statusText = ["Progressing", "Paid", "Progressing", "Cancelled"]; // 0, 1, 2, 3

  console.log(statusText[status] ?? "Initiated");

  return statusText[status] ?? "Initiated";
}

export function getGasLimits() {
  let web3Connect = new Web3(config.get<string>("rpcUrl"));
  return web3Connect.eth.getGasPrice().then((result) => {
    return web3Connect.utils.fromWei(result, "ether");
  });
}

export function uploadUrl(hostname: any) {
  let url: any =
    hostname == "localhost"
      ? "http://" + hostname + "/"
      : "https://" + hostname + "/";
  return url;
}

export async function readFile(filename: File) {
  try {
    // ✅ Read contents of directory
    const dirContents = await fsPromises.readdir(__dirname);
    console.log(dirContents);

    // ✅ Read contents of `another-file.ts` in the same directory
    const fileContents = await fsPromises.readFile(
      path.join(__dirname, "./another-file.ts"),
      { encoding: "utf-8" }
    );
    console.log(fileContents);
  } catch (err) {
    console.log("error is: ", err);
  }
}
Back to Directory File Manager