File: /var/www/api.javaapp.co.uk/src/helper/index.js
import UserDB from "../models/users.model.js"
import { Op } from "sequelize"
import moment from "moment"
import fs from "fs"
import sendNotif from "./firebase/firebase_admin.js";
export async function getProfilePicture(filename, name = "SH") {
if (filename === "" || filename === undefined || filename === null) {
filename =
"https://ui-avatars.com/api/?name=" +
name +
"&rounded=true&background=c39a56&color=fff";
} else {
filename = filename;
}
filename = filename.replace(/\\/g, "/");
return filename;
}
export async function generateRandomString(length, isNumber = false) {
var result = "";
if (isNumber) {
var characters = "0123456789";
} else {
var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
}
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
export async function writeErrorLog(req, error) {
const requestURL = req.protocol + "://" + req.get('host') + req.originalUrl;
const requestBody = JSON.stringify(req.body);
const date = moment().format('MMMM Do YYYY, h:mm:ss a');
fs.appendFileSync('errorLog.log', "REQUEST DATE : " + date + "\n" + "API URL : " + requestURL + "\n" + "API PARAMETER : " + requestBody + "\n" + "Error : " + error + "\n\n");
}
export async function sendPushNotification(user_id, title, body, notification_type, otherData) {
try {
let userData = await UserDB.findOne({
where: {
id: parseInt(user_id),
device_type: {
[Op.in]: [1, 2]
},
notification_status: 1
},
attributes: [
'fcm_token', 'device_type'
]
});
if (userData && userData.fcm_token) {
const message = {
token: userData.fcm_token,
notification: {
title: title,
body: body,
},
android: {
notification: {
sound: "default",
},
data: {
title: title,
message: body,
notification_type: notification_type.toString(),
cafe_id: (notification_type == 2) ? (otherData.cafe_id).toString() : '',
group_id: (notification_type == 2) ? (otherData.group_id).toString() : '',
request_endtime: (notification_type == 2) ? (otherData.request_endtime).toString() : '',
},
},
};
sendNotif(message);
}
} catch (error) {
console.log(error)
}
}
export function haversine(latitude, longitude) {
return `(
3959 * acos(
cos(radians(${latitude}))
* cos(radians(latitude))
* cos(radians(longitude) - radians(${longitude}))
+ sin(radians(${latitude})) * sin(radians(latitude))
)
)`;
}