Skip to content

Commit

Permalink
bg(validations): fix trip creation validations
Browse files Browse the repository at this point in the history
  • Loading branch information
hezronkimutai committed Feb 20, 2020
1 parent 0c416b6 commit 2e55a12
Show file tree
Hide file tree
Showing 15 changed files with 99 additions and 36 deletions.
4 changes: 2 additions & 2 deletions src/controllers/NotificationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ class AccommodationController {
const { notificationIds } = req.body;
const { notificationId } = req.params;
const notificationArr = req.params.notificationId
? notificationIds.filter(id => id === parseInt(notificationId, 10))
: notificationIds;
? notificationId
: notificationIds.filter(id => id === parseInt(id, 10));
await markNotificationAsRead(notificationArr);
return Response.successMessage(req, res, 'Notification marked as read successfully', '', 201);
} catch (err) {
Expand Down
1 change: 1 addition & 0 deletions src/controllers/TripController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Response from '../helpers/Response';
import TripHelper from '../helpers/TripHelper';
import NotificationService from '../services/NotificationService';


const { availtripRequestsToManager, getUserRequests, getTripTypes } = TripService;
const { createNewTrip } = TripHelper;
/**
Expand Down
10 changes: 5 additions & 5 deletions src/helpers/notificationConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ const notificationEvents = (eventName, clientData) => {
eventEmitters.emit(eventName, JSON.stringify(clientData));
};

const sendNotification = (io, emitterEvent, socketEvent) => {
io.on('connection', (socket) => {
eventEmitters.on(emitterEvent, (data) => {
socket.emit(socketEvent, data);
const sendNotification = (io, socketEvent, connectedClients, data) => {
if (connectedClients[data.userId.toString()]) {
connectedClients[data.userId.toString()].forEach(client => {
io.to(client).emit(socketEvent, data);
});
});
}
};

export {
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/socketIo.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { sendNotification } from './notificationConfig';
const socketIo = (server) => {
const io = socketIO(server);
io.use((sockets, next) => {

if (sockets) {
sockets.socket = sockets;
next();
Expand All @@ -16,7 +17,6 @@ const socketIo = (server) => {
sendNotification(io, 'post_comment_notification', 'post_comment_client');
sendNotification(io, 'booking_notification', 'booking_client');
sendNotification(io, 'trip_request_notification', 'trip_request_client');

return io;
};

Expand Down
44 changes: 35 additions & 9 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,52 @@ import express from 'express';
import bodyParser from 'body-parser';
import path from 'path';
import cors from 'cors';
import socketIo from 'socket.io';
import sendNotif from './helpers/socketIo';
import router from './routes';
import socketIo from './helpers/socketIo';
import tokenHelpers from './middlewares/ForgotPasswordMiddlewares';
import { sendNotification } from './helpers/notificationConfig';


const app = express();
const port = process.env.PORT || 3000;


app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: 'application/json' }));
app.use('/static', express.static(path.join(__dirname, 'public')));

const server = app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`Server is running on PORT ${port}....`);
});

const io = socketIo(server);

const connectedClients = {};
io.use((socket, next) => {
const { token } = socket.handshake.query;
try {
const userData = tokenHelpers.decodeTokenHelper(token);
if (userData) {
const clientKey = Number.parseInt(userData.id, 10);
connectedClients[clientKey] = connectedClients[clientKey] || [];
connectedClients[clientKey].push(socket.id);
}
next();
} catch (error) {
return (error);
}
});

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

app.use('/', router);

app.get('/', (req, res) => res.status(200).send({
Expand All @@ -24,12 +58,4 @@ app.use('*', (req, res) => res.status(404).send({
}));


const server = app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`Server is running on PORT ${port}....`);
});

socketIo(server);


export default app;
15 changes: 15 additions & 0 deletions src/middlewares/ForgotPasswordMiddlewares.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,21 @@ class ForgotPasswordMiddlewares {
}
}

/**
* decode token middleware
* @static
* @param {Object} token token
* @returns {Object} returns a response error if error exists or returns a token if exists
*/
static decodeTokenHelper(token) {
try {
const verifiedUser = jwt.verify(token, process.env.JWT_KEY);
return verifiedUser;
} catch (error) {
return error;
}
}

/**
* Validate forgot password input
* @static
Expand Down
3 changes: 2 additions & 1 deletion src/middlewares/Validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@ class Validate {
const MaxDate = new Date(year + 20, month, day).toDateString();
return [
check('tripTypeId', 'trip type id should be an integer(1: One-way, 2: two-way, 3: Multi-city)').isInt(),
check('user', 'user should be identified by id of integer type').isInt().optional(),
check('from', 'To date should be valid(YYYY-MM-DD)').isBefore(MaxDate),
check('to', 'End date should be valid(YYYY-MM-DD)').isBefore(MaxDate),
];
Expand Down Expand Up @@ -365,7 +366,7 @@ class Validate {
static validateNotificationIdRules() {
return [
check('notificationId', 'The notificationId should be an integer').isInt().optional(),
check('notificationIds', 'The notificationIds should be an array').isArray(),
check('notificationIds', 'The notificationIds should be an array').isArray().optional(),
check('notificationIds.*', 'The notification IDs should be integer').isInt()
];
}
Expand Down
7 changes: 7 additions & 0 deletions src/services/AccommodationService.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ class AccommodationService {
setObject = { disliked: true, liked: false };
displayMessage = 'You disliked this accommodation!';
}
if (like && !liked && disliked) {
setObject = { disliked: false, liked: true };
displayMessage = 'You liked this accommodation!';
}
if (!liked && !disliked) {
setObject = { liked: like, disliked: !like };
displayMessage = like ? 'You liked this accommodation!' : 'You disliked this accommodation!';
Expand Down Expand Up @@ -259,6 +263,9 @@ class AccommodationService {
}]
}
: {
order: [
['updatedAt', 'DESC'],
],
include: [{
model: rooms, as: 'accommodationRooms'
}, { model: accommodationImages, as: 'imagesAccommodation' },
Expand Down
3 changes: 3 additions & 0 deletions src/services/BookingService.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ class BookingService {
};
const findOneBookingOb = {
where: id ? { id } : {},
order: [
['updatedAt', 'DESC'],
],
include: [{
model: trips,
include: [{
Expand Down
3 changes: 3 additions & 0 deletions src/services/CommentService.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ class CommentService {
const { tripRequestId } = req.params;
const queryObj = {
attributes: ['id', 'comment', 'updatedAt'],
order: [
['updatedAt', 'ASC'],
],
include: [
{
model: users,
Expand Down
27 changes: 13 additions & 14 deletions src/services/NotificationService.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
booking,
sequelize
} from '../database/models';
import { notificationEvents } from '../helpers/notificationConfig';
import { notificationEvents, sendNotification } from '../helpers/notificationConfig';

dotenv.config();

Expand Down Expand Up @@ -53,6 +53,7 @@ class NotificationService {
updatedAt
};
notificationEvents('approve_reject_notification', { message, data });
sendNotification(req.io, 'approve_reject_notification', req.connectedClients, result);
}

/**
Expand Down Expand Up @@ -102,6 +103,7 @@ class NotificationService {
updatedAt
};
notificationEvents('edit_trip_notification', { message, data });
sendNotification(req.io, 'edit_trip_notification', req.connectedClients, result);
}

/**
Expand Down Expand Up @@ -132,29 +134,24 @@ class NotificationService {
let receiverId;

if (userId === user.id) {
receiverId = managerId; // is a manage
receiverId = managerId;
} else {
receiverId = userId; // is a user
receiverId = userId;
}

const result = await NotificationService.saveNotification({
userId: receiverId,
commentsId: params.tripRequestId,
tripRequestId: params.tripRequestId,
message
});

const data = {
notificationId: result.dataValues.id,
commentsId: params.tripRequestId,
tripRequestId: params.tripRequestId,
updatedAt: result.dataValues.updatedAt
};
notificationEvents('post_comment_notification', { message, data });
NotificationService.saveNotification({
userId,
tripRequestId: params.tripRequestId,
message
});
notificationEvents('approve_reject_notification', { message, data });
notificationEvents('post_comment_notification', { data });
sendNotification(req.io, 'post_comment_notification', req.connectedClients, result);
}

/**
Expand All @@ -176,13 +173,14 @@ class NotificationService {
const tripUser = await CommonQueries.findAll(userProfile, managerIdqueryObject);
const message = `${tripUser[0]['user.firstName']} ${tripUser[0]['user.lastName']} has made an new travel request`;
const newNotification = await NotificationService.saveNotification({
userId: req.user.id,
userId: tripUser[0].managerId,
message,
tripRequestId: req.result.id
});
const { bookingId, updatedAt, ...data } = newNotification.dataValues;
data.managerId = tripUser.managerId;
data.managerId = tripUser[0].managerId;
notificationEvents('trip_request_notification', { data });
sendNotification(req.io, 'trip_request_notification', req.connectedClients, data);
}


Expand Down Expand Up @@ -222,6 +220,7 @@ class NotificationService {
data.travelAdminId = accommodation[0]['room.accommodation.userId'];

notificationEvents('booking_notification', { data });
sendNotification(req.io, 'booking_notification', req.connectedClients, data);
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/services/TripService.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ class TripService {
const managerRequestsObj = {
where: { userId: user.userId, statusId: 1 },
attributes: ['id', 'updatedAt', 'createdAt'],
order: [
['updatedAt', 'DESC'],
],
include: [
{
model: trips,
Expand Down Expand Up @@ -120,7 +123,9 @@ class TripService {
static async getUserRequests(req) {
const requestsUsersObject = {
where: { userId: req.user.id },

order: [
['updatedAt', 'DESC'],
],
include: [{
model: trips,
},
Expand Down
3 changes: 3 additions & 0 deletions src/services/UserService.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ class UserService {
static async availableUsers() {
const allUsersObj = {
attributes: ['id', 'firstName', 'lastName', 'email', 'roleId'],
order: [
['updatedAt', 'DESC'],
],
include: [
{
model: roles,
Expand Down
4 changes: 2 additions & 2 deletions src/tests/060-tripTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -569,8 +569,8 @@ describe('User stats for trips in X timeframe', () => {
.get('/api/v1/trips/stats/2?from=2020-01-01&to=2025-12-30&user=b')
.set('token', managerToken)
.end((err, res) => {
expect(res.status).eql(500);
expect(res.body).to.have.property('message', 'invalid input syntax for integer: "b"');
expect(res.status).eql(400);
expect(res.body.message).eql(['user should be identified by id of integer type']);
done(err);
});
});
Expand Down
2 changes: 1 addition & 1 deletion src/tests/110-notificationTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ describe('Notification tests', () => {
});
});
it('A user should be able to mark one notification as read', (done) => {
chai.request(app).patch('/api/v1/notifications/markRead/11')
chai.request(app).patch('/api/v1/notifications/markRead')
.set('token', userToken1)
.send(notificationIds)
.end((err, res) => {
Expand Down

0 comments on commit 2e55a12

Please sign in to comment.