Initial Version
This commit is contained in:
1
server/middlewares/helpers/asyncErrorHandler.js
Normal file
1
server/middlewares/helpers/asyncErrorHandler.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports=(e=>(o,r,s)=>{Promise.resolve(e(o,r,s)).catch(s)});
|
||||
33
server/middlewares/helpers/createNotification.js
Normal file
33
server/middlewares/helpers/createNotification.js
Normal file
@@ -0,0 +1,33 @@
|
||||
const Notification = require("../../models/Notification")
|
||||
const SocketMapping = require("../../models/SocketMapping")
|
||||
const {dropRight} = require("lodash")
|
||||
module.exports = async (io, adminId,notificationObj) => {
|
||||
//notify to the admin through socket.io
|
||||
//first save notification
|
||||
let notificationObjOfAdmin = await Notification.findOne({ admin:adminId })
|
||||
if (!notificationObjOfAdmin) {
|
||||
// create new notification
|
||||
notificationObjOfAdmin = new Notification({
|
||||
admin:adminId,
|
||||
notifications: [notificationObj],
|
||||
noOfUnseen: 1
|
||||
})
|
||||
await notificationObjOfAdmin.save()
|
||||
} else {
|
||||
let notifications = notificationObjOfAdmin.notifications
|
||||
notifications.unshift(notificationObj)
|
||||
notificationObjOfAdmin.noOfUnseen += 1
|
||||
if (notificationObjOfAdmin.noOfUnseen < 20 && notifications.length > 20) {
|
||||
notificationObjOfAdmin.notifications = dropRight(notifications, notifications.length - 20 )
|
||||
}
|
||||
await notificationObjOfAdmin.save()
|
||||
}
|
||||
//now notifying to the admin
|
||||
let socketUser = await SocketMapping.find({ user:adminId })
|
||||
if (socketUser.length) {
|
||||
//for every same login user emit notification
|
||||
socketUser.forEach(u => {
|
||||
io.to(u.socketId).emit('notification', { noOfUnseen: notificationObjOfAdmin.noOfUnseen });
|
||||
})
|
||||
}
|
||||
}
|
||||
21
server/middlewares/helpers/dbConnection.js
Normal file
21
server/middlewares/helpers/dbConnection.js
Normal file
@@ -0,0 +1,21 @@
|
||||
const mongoose = require("mongoose");
|
||||
const Fawn = require("fawn");
|
||||
|
||||
module.exports = () => {
|
||||
const self = module.exports;
|
||||
mongoose
|
||||
.connect(process.env.MONGO_URI, {
|
||||
useNewUrlParser: true,
|
||||
useCreateIndex: true,
|
||||
useUnifiedTopology: true,
|
||||
useFindAndModify: false
|
||||
})
|
||||
.then(() => console.log("DB Connected"))
|
||||
.catch(err => {
|
||||
console.error(
|
||||
"Failed to connect to the database on startup - retrying in 5 sec"
|
||||
);
|
||||
setTimeout(self, 5000);
|
||||
});
|
||||
return Fawn.init(mongoose,process.env.TRANS_COLL)
|
||||
};
|
||||
1
server/middlewares/helpers/dbErrorHandler.js
Normal file
1
server/middlewares/helpers/dbErrorHandler.js
Normal file
@@ -0,0 +1 @@
|
||||
"use strict";const uniqueMessage=e=>{let s;try{let r=e.message.substring(e.message.lastIndexOf(".$")+2,e.message.lastIndexOf("_1"));s=r.charAt(0).toUpperCase()+r.slice(1)+" already exists"}catch(e){s="Unique field already exists"}return s};exports.errorHandler=(e=>{let s="";if(e.code)switch(e.code){case 11e3:case 11001:s=uniqueMessage(e)}else{-1!==e.message.indexOf("Cast to ObjectId failed")&&(s="No data found");for(let r in e.errors)e.errors[r].message&&(s=e.errors[r].message)}return s.includes("Path")&&(s=s.slice(6)),s});
|
||||
22
server/middlewares/helpers/fileRemover.js
Normal file
22
server/middlewares/helpers/fileRemover.js
Normal file
@@ -0,0 +1,22 @@
|
||||
const fs = require("fs");
|
||||
|
||||
module.exports = files => {
|
||||
return Promise.all(
|
||||
files.map(
|
||||
file =>
|
||||
new Promise((res, rej) => {
|
||||
try {
|
||||
setTimeout(() => {
|
||||
fs.unlink(file, err => {
|
||||
if (err) throw err;
|
||||
res();
|
||||
});
|
||||
}, 10000);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
rej(err);
|
||||
}
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
19
server/middlewares/helpers/geoDistance.js
Normal file
19
server/middlewares/helpers/geoDistance.js
Normal file
@@ -0,0 +1,19 @@
|
||||
module.exports = (lon1, lat1, lon2, lat2) => {
|
||||
// mean radius of earth's = 6,371km
|
||||
const R = 6371;
|
||||
// distance between latitude and longitude in radians
|
||||
const dLat = ((lat2 - lat1) * Math.PI) / 180;
|
||||
const dLon = ((lon2 - lon1) * Math.PI) / 180;
|
||||
// haversine’ formula to calculate distance
|
||||
const a =
|
||||
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||
Math.cos((lat1 * Math.PI) / 180) *
|
||||
Math.cos((lat2 * Math.PI) / 180) *
|
||||
Math.sin(dLon / 2) *
|
||||
Math.sin(dLon / 2);
|
||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
const d = R * c;
|
||||
// if (d > 1) return Math.round(d) + "km";
|
||||
// else if (d <= 1) return Math.round(d * 1000) + "m";
|
||||
return d;
|
||||
};
|
||||
1
server/middlewares/helpers/imageCompressor.js
Normal file
1
server/middlewares/helpers/imageCompressor.js
Normal file
@@ -0,0 +1 @@
|
||||
const Jimp=require("jimp"),path=require("path");module.exports=(async(e,r,i,o,t)=>(Jimp.read(i).then(i=>{i.resize(r,Jimp.AUTO).write(path.resolve(o,`${t}`,e))}).catch(e=>{console.log("Error at reducing size / converting picture : "),console.log(e)}),`${t}/${e}`));
|
||||
24
server/middlewares/helpers/mailer.js
Normal file
24
server/middlewares/helpers/mailer.js
Normal file
@@ -0,0 +1,24 @@
|
||||
const nodeMailer = require("nodemailer");
|
||||
|
||||
exports.sendEmail = mailingData => {
|
||||
const transporter = nodeMailer.createTransport({
|
||||
host: "smtp.gmail.com",
|
||||
port: 587,
|
||||
secure: false,
|
||||
requireTLS: true,
|
||||
auth: {
|
||||
user: process.env.ECOM_EMAIL,
|
||||
pass: process.env.ECOM_PASSWORD
|
||||
}
|
||||
});
|
||||
return transporter
|
||||
.sendMail(mailingData)
|
||||
.then(info =>{
|
||||
console.log(`Message sent: ${info.response}`)
|
||||
})
|
||||
.catch(err => {
|
||||
console.log(`Problem sending email: ${err}`)
|
||||
err.message ='There was a problem while sending a email'
|
||||
throw err
|
||||
});
|
||||
};
|
||||
53
server/middlewares/helpers/multer.js
Normal file
53
server/middlewares/helpers/multer.js
Normal file
@@ -0,0 +1,53 @@
|
||||
const path = require("path");
|
||||
const multer = require("multer");
|
||||
|
||||
|
||||
//user's..
|
||||
const storageByUser = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, './public/uploads')
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
cb(null, file.fieldname + '-' + req.user._id + '-' + Date.now() + path.extname(file.originalname))
|
||||
}
|
||||
})
|
||||
|
||||
//admin's..
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, './public/uploads')
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
cb(null, file.fieldname + '-' + req.profile._id + '-' + Date.now() + path.extname(file.originalname))
|
||||
}
|
||||
})
|
||||
//superadmin's..
|
||||
const storageBySuperAdmin = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, './public/uploads')
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
cb(null, file.fieldname + '-' + req.admin.role +req.admin._id + '-' + Date.now() + path.extname(file.originalname))
|
||||
}
|
||||
})
|
||||
|
||||
const fileFilter = (req, file, callback) => {
|
||||
const ext = path.extname(file.originalname);
|
||||
if (ext !== '.png' && ext !== '.jpg' && ext !== '.JPG' && ext !== '.jpeg') {
|
||||
return callback(new Error('Not Image'))
|
||||
}
|
||||
callback(null, true)
|
||||
}
|
||||
const limits = { fileSize: 2480 * 3230 }
|
||||
|
||||
// exports.uploadAdminDoc = multer({ storage, fileFilter, limits }).fields([
|
||||
// { name: "citizenshipFront", maxCount: 1 },
|
||||
// { name: "citizenshipBack", maxCount: 1 },
|
||||
// { name: "businessLicence", maxCount: 1 }
|
||||
// ]);
|
||||
exports.uploadAdminDoc = multer({ storage,fileFilter,limits }).single("doc");
|
||||
exports.uploadAdminPhoto = multer({ storage, fileFilter, limits }).single("photo");
|
||||
exports.uploadUserPhoto = multer({ storage: storageByUser, fileFilter, limits }).single("photo");
|
||||
|
||||
exports.uploadProductImages = multer({ storage, fileFilter, limits }).array("productImages",5)
|
||||
exports.uploadBannerPhoto = multer({ storage:storageBySuperAdmin ,fileFilter, limits: { fileSize: 8480 * 4230 } }).single("bannerPhoto")
|
||||
41
server/middlewares/helpers/waterMarker.js
Normal file
41
server/middlewares/helpers/waterMarker.js
Normal file
@@ -0,0 +1,41 @@
|
||||
const Jimp = require('jimp');
|
||||
module.exports = async (req,res,next) => {
|
||||
if (!req.files.length) {
|
||||
return next()
|
||||
}
|
||||
const options = {
|
||||
ratio: 0.6,
|
||||
opacity: 0.4,
|
||||
text: 'K I N D E E M',
|
||||
textSize: Jimp.FONT_SANS_64_BLACK,
|
||||
}
|
||||
const getDimensions = (H, W, h, w, ratio) => {
|
||||
let hh, ww;
|
||||
if ((H / W) < (h / w)) { //GREATER HEIGHT
|
||||
hh = ratio * H;
|
||||
ww = hh / h * w;
|
||||
} else { //GREATER WIDTH
|
||||
ww = ratio * W;
|
||||
hh = ww / w * h;
|
||||
}
|
||||
return [hh, ww];
|
||||
}
|
||||
let results = req.files.map(async file=>{
|
||||
const watermark = await Jimp.read('./public/uploads/logo.png');
|
||||
const imagePath = file.path
|
||||
|
||||
const main = await Jimp.read(imagePath);
|
||||
const [newHeight, newWidth] = getDimensions(main.getHeight(), main.getWidth(), watermark.getHeight(), watermark.getWidth(), options.ratio);
|
||||
watermark.resize(newWidth, newHeight);
|
||||
const positionX = ((main.getWidth() - newWidth) / 2)+250;
|
||||
const positionY = ((main.getHeight() - newHeight) / 2+200);
|
||||
watermark.opacity(options.opacity);
|
||||
main.composite(watermark,
|
||||
positionX,
|
||||
positionY,
|
||||
Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE);
|
||||
return main.quality(100).write(imagePath);
|
||||
})
|
||||
await Promise.all(results)
|
||||
next()
|
||||
}
|
||||
Reference in New Issue
Block a user