Skip to content

Commit

Permalink
chore(notifications): Live Notifications
Browse files Browse the repository at this point in the history
- use socket to emit on notification

[Finishes #]
  • Loading branch information
nignanthomas committed Jan 13, 2020
1 parent c4c1cad commit 455fda4
Show file tree
Hide file tree
Showing 9 changed files with 96 additions and 8 deletions.
3 changes: 2 additions & 1 deletion src/controllers/accommodationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ export default class AccommodationController {
const newBooking = await models.booking.create(bookingData);

await notifSender(
req,
'Accommodation Booked',
newBooking,
accommodation[0].owner,
Expand Down Expand Up @@ -280,7 +281,7 @@ export default class AccommodationController {
await bookingHelper.updateAccomodation(req, remainingSpace);
}

await notifSender(subject, booking, booking.userId, APP_URL_BACKEND, activity, 'booking', host);
await notifSender(req, subject, booking, booking.userId, APP_URL_BACKEND, activity, 'booking', host);
return responseHelper(res, responseMessage, null, 200);
}
return responseHelper(res, strings.accommodations.error.BOOKING_NOT_FOUND, null, 404);
Expand Down
1 change: 1 addition & 0 deletions src/controllers/chatController.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,5 @@ const viewPrivateChats = async (req, res) => {
EMPTY_HISTORY : CHAT_HISTORY, privateChats);
};


export default { chat, viewChats , viewPrivateChats};
2 changes: 1 addition & 1 deletion src/controllers/commentsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default class CommentsController {
userNotiified,
`A comment has been made on request ${requestId}. Click here to view: ${APP_URL_BACKEND}/api/v1/requests/${requestId}.`,
);
await notifSaver(notification);
await notifSaver(req, notification);
const {
deleted, userId,
...data
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/destinationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default class destinationController {

const { lineManager } = user.payload;

await notifSender('Request Created', request, lineManager, APP_URL_BACKEND, 'created', 'request', host);
await notifSender(req, 'Request Created', request, lineManager, APP_URL_BACKEND, 'created', 'request', host);

return Utilities.responseHelper(
res,
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/requestController.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export default class requestController {

request = request[1][0].dataValues;

await notifSender(subject, request, request.userId, APP_URL_BACKEND, activity, 'request', host);
await notifSender(req, subject, request, request.userId, APP_URL_BACKEND, activity, 'request', host);
return responseHelper(res, responseMessage, null, 200);
}
return responseHelper(res, strings.requests.NOT_FOUND, null, 404);
Expand Down Expand Up @@ -123,7 +123,7 @@ export default class requestController {

const request = await allSearch({ id });
const requestData = request[0].dataValues;
await notifSender('Request Edited', requestData, lineManager, APP_URL_BACKEND, 'edited', 'request');
await notifSender(req, 'Request Edited', requestData, lineManager, APP_URL_BACKEND, 'edited', 'request');
return responseUtil(res, 200, strings.request.success.SUCCESS_UPDATE_REQUEST, request);
} catch (error) {
return res.status(500).json({ error: 'Something wrong' });
Expand Down
6 changes: 4 additions & 2 deletions src/helpers/notifSender.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ const transporter = nodemailer.createTransport({
}
});

const notifSender = async (subject, object, userId, APP_URL_BACKEND, activity, table, host) => {
const notifSender = async (
req, subject, object, userId, APP_URL_BACKEND, activity, table, host
) => {
try {
const user = await findUser({ id: userId });
let URL;
Expand All @@ -33,7 +35,7 @@ const notifSender = async (subject, object, userId, APP_URL_BACKEND, activity, t
if (user.appNotif) {
const notification = await notifBuilder(table, object.id, userId, activityMessage);
try {
await notifSaver(notification);
await notifSaver(req, notification);
} catch (error) {
return error;
}
Expand Down
55 changes: 55 additions & 0 deletions src/helpers/socketNotif.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import jwt from 'express-jwt';
import io from '../index';

const socketNotif = notification => {
const onlineUsers = [];
const getLoggedInUser = (token, socket) => {
if (token === null) {
socket.emit('connection_error', 'Token not present');
}
try {
const user = jwt.verify(token, process.env.JWT_SECRET);
const userObject = {
socketId: socket.id,
userId: user.payload.id,
email: user.payload.email
};

const filter = onlineUsers.filter(client => client.userId === user.payload.id);

if (filter.length === 0) {
onlineUsers.push(userObject);
} else {
onlineUsers.forEach(client => {
if (client.userId === user.payload.id) {
client.socketId = socket.id;
}
});
}
return user;
} catch (error) {
socket.emit('connection_error', error.message);
}
};

try {
io.use((socket, next) => {
const { token } = socket.request._query;
const user = getLoggedInUser(token, socket);
socket.user = user;
next();
});
} catch (error) {
socket.emit('connection_error', error.message);
}

if (!receiverId) {
io.emit(entity, data);
} else if (connectedClients[receiverId.toString()]) {
connectedClients[receiverId.toString()].forEach(element => {
io.to(element).emit(entity, data);
});
}
};

export default socketNotif;
20 changes: 20 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,24 @@ app.use('*', (req, res) => {
// eslint-disable-next-line no-console
http.listen(port, () => console.log(`Barefoot Nomad is runnig server on port ${port}...`));

// const connectedClients = {};
// io.use((socket, next) => {
// const { token } = socket.handshake.query;
// const userData = validateToken(token);
// if (userData) {
// const clientKey = Number.parseInt(userData.userId, 10);
// connectedClients[clientKey] = connectedClients[clientKey] || [];
// connectedClients[clientKey].push(socket.id);
// }
// next();
// });

// app.use((req, res, next) => {
// req.io = io;
// req.connectedClients = connectedClients;
// next();
// });

export { io };

export default app;
11 changes: 10 additions & 1 deletion src/services/notifServices.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
/* eslint-disable require-jsdoc */
import moment from 'moment';
import models from '../database/models';
import socketNotif from '../helpers/socketNotif';
import { io } from '../index';

export default class notifServices {
static async notifSaver(notif) {
static async notifSaver(req, notif) {
const notification = await notif.save();
try {
// socketNotif(notification.userNotified, notification, req.connectedClients, req.io, 'notification');
io.emit('notification', notification);
console.log('sockectNotif ===> ', io.emit('notification', notification));
} catch (error) {
// console.log('sockectNotif error ===> ', error);
}
return notification;
}

Expand Down

0 comments on commit 455fda4

Please sign in to comment.