Skip to content

Instantly share code, notes, and snippets.

@Billmike
Created January 11, 2019 08:26
Show Gist options
  • Save Billmike/7bf9cf3bc610a5df8f028a070897c22c to your computer and use it in GitHub Desktop.
Save Billmike/7bf9cf3bc610a5df8f028a070897c22c to your computer and use it in GitHub Desktop.
class Events {
/**
* Adds an event to the database
*
* @param {object} request - The request object
* @param {object} response - The response object
*
* @returns {object} The event object
*/
static addEvent(request, response) {
const { errors, valid } = validateAddEvent(request.body);
if (!valid) {
return response.status(400).json(errors);
}
return Center.findOne({
where: {
name: request.body.venue
}
}).then((foundCenter) => {
if (!foundCenter) {
return response.status(400).json({
message: 'No center found with this name.'
});
}
const duration = timeDifference(
request.body.startTime,
request.body.endTime
);
const convertStartTime = new Date(request.body.startTime)
.toLocaleTimeString('en-US', { hour12: false });
const convertEndTime = new Date(request.body.endTime)
.toLocaleTimeString('en-US', { hour12: false });
const eventDuration =
`${duration.hours}hour(s), ${duration.minutes}minutes`;
return Event.findAll({
where: {
date: request.body.date,
venue: foundCenter.dataValues.id
}
}).then((foundEvent) => {
for (let index = 0; index < foundEvent.length; index += 1) {
const event = foundEvent[index];
if ((convertStartTime >= event.dataValues.startTime
&& convertStartTime <= event.dataValues.endTime) ||
(convertEndTime <= event.dataValues.endTime
&& convertEndTime >= event.dataValues.startTime)) {
return response.status(409).json({
message:
`Sorry, you cannot book an event at this
time because there will be an event
holding between ${event.dataValues.startTime} and ${event.dataValues.endTime}.`
});
}
}
return Event.create({
name: request.body.name,
image: request.body.image,
date: request.body.date,
startTime: request.body.startTime,
endTime: request.body.endTime,
duration: eventDuration,
organizer: request.userDetails.id,
venue: foundCenter.dataValues.id
}).then((event) => {
return response.status(201).json({
message: 'Event created successfully.',
eventDetails: {
name: event.name,
image: event.image,
date: event.date,
startTime: event.startTime,
endTime: event.endTime,
duration: event.duration,
venue: foundCenter.dataValues.name
}
});
});
});
}).catch((err) => {
return response.status(500).json({
message: serverError
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment