File: //var/www/javago_test/src/helper/index.js
import UserDB from "../models/users.model.js"
import { Op } from "sequelize"
import moment from "moment"
import fs from "fs"
import FCM from "fcm-push"
const fcm = new FCM("AAAASBkjhKw:APA91bGhCfnGhTXKkoi-9XNsw3yQ352h7l_kQZQ7Gd2iR5NR6n1jCjfl61us_auJsJmTayc2xeGmyawC4y2qoyjku2GhnZENczp7Dt-Q4jb0dOjAhISQGtlhjzvf7UuaObdBdBnXil6z")
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) {
let notification_message
notification_message = {
registration_ids: [userData.fcm_token],
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() : '',
},
notification: {
title: title,
body: body,
sound: 'default',
}
}
fcm.send(notification_message, function (err2, response) {
if (err2) {
console.log('-----------------------------------------------------------------');
console.log('New Message Notification Error :: ');
console.log(err2);
console.log('-----------------------------------------------------------------');
} else {
console.log('-----------------------------------------------------------------');
console.log('New Message Notification Success :: ');
console.log(response);
console.log('-----------------------------------------------------------------');
}
})
}
} catch (error) {
console.log(error)
}
}