Skip to content

Commit

Permalink
create enrollment endpoint POST #44 🎈
Browse files Browse the repository at this point in the history
  • Loading branch information
mrmorais committed Oct 31, 2017
1 parent 222362b commit 09af074
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 4 deletions.
61 changes: 60 additions & 1 deletion src/controllers/event/Event.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import EventDAO from './EventDAO';
import EventModel from '../../models/event.model';
import FieldError from '../FieldError';

import RoleModel from '../../models/role.model';
import RelationshipModel from '../../models/relationship.model';

import * as EventHelper from './EventHelper';

/**
* Event
* @@ Event
* Stores and manipulates Event Database Object
*
* @ Log:
* Maradona Morais '2017-10-31 15:55' >> Defines the methods enroll() and createRelationship()
* with pendences, please see the issue #44
*/
export default class {
/**
Expand Down Expand Up @@ -140,6 +147,58 @@ export default class {
});
}

/**
* Enrolls a user in the event based on a role id
* @param user user to be enrolled
* @param roleId event's role id that the user will have
*/
enroll(user, roleId) {
return new Promise((resolve, reject) => {
// find the role in event object
const role = this.eventObject.ofRoles.id(roleId);

if (role === undefined || role.type === 'private') {
// The role doesn't exists or it is invalid to enroll on
reject('Papel não encontrado');
} else {
// The role exists, then create a relationship
this.createRelationship(user, role);
this.store()
.then(() => {
resolve();
});
}
});
}

/**
* Creates a relationship between a user and the event by atributting a event's role to
* the passed user
* @param user user to be related to
* @param role event's role to relate the user with
*/
createRelationship(user, role) {
const relationshipIdx = this.eventObject.ofRelationships.findIndex((currRelationship) => {
return currRelationship.user === user.userObject._id;
});

if (relationshipIdx === -1) { // Not found relationship
// Create a new one
const newRelationship = new RelationshipModel({
user: user.userObject._id,
ofRoles: [role._id],
});
this.eventObject.ofRelationships.push(newRelationship);
} else {
// Already has a role set, just append a new role into it
this.eventObject.ofRelationships[relationshipIdx].ofRoles.push(role._id);
// TODO: The user class must have a method called addEventToList (or similar)
// to add the reference to the current event in the user's Array ofEvents
// TODO: What if the user already have a public relationship with this event?
// Whats the best way to figure this out?
}
}

/**
* Insert a event in db
* @return Promise. Resolve(set event values on), Reject(Error)
Expand Down
45 changes: 42 additions & 3 deletions src/controllers/event/EventRouter.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import { Router } from 'express';
import Event from './Event';
import User from '../user/User';
import Response from '../Response';
import { simpleAuthorization } from '../authorization/Authorization';
import * as Constants from './constants';

/**
* @@ Event Express Router
* Routers paths to '/api/event' prefix
*
* @ Log:
* Maradona Morais '2017-10-31' >> Create the path to enroll a user into the event
*/
const eventRouter = Router();

/**
Expand All @@ -21,13 +31,15 @@ eventRouter.post('/', (req, res) => {
res.json(Response(true, {}, err));
});
}).catch((data) => {
res.status(400).json(Response(true, data, 'Erro ao fazer cadastro'));
res.status(400).json(Response(true, data, Constants.EVENT_CREATION_ERROR_MSG));
});
});

/**
* Returns a set of events
* See a rich documentation in '/docs/evento.br.md'
*
* @MissingTests
*/
eventRouter.get('/', (req, res) => {
const page = (req.query.page) ? parseInt(req.query.page, 10) : 1;
Expand All @@ -36,18 +48,45 @@ eventRouter.get('/', (req, res) => {
const fields = (req.query.fields) ? req.query.fields : 'name,subtitle,location,eventPeriod,enrollmentPeriod,published';
const order = (req.query.order) ? req.query.order : '-createdAt'; // News events first
const published = (req.query.published) ? req.query.published : true;
// By default returns publisheds events
// By default returns published events

Event.loadEvents(page, count, query, fields, order, published)
.then((eventSet) => {
res.json(Response(false, eventSet));
});
});

/**
* Allows to a user enroll a event by selecting a public role
* @param id event id to be enrolled onto
* @param role the event's public role id (please see /docs/papel.br.md)
*
* @MissingTests
*/
eventRouter.post('/:id/enroll', simpleAuthorization, (req, res) => {
const roleId = req.body.role; // The role id that the user wants to enroll with

// Load the logged user in a User object by the id
const user = new User();
user.loadById(res.locals.user._id);

// Load the current event by the id
const event = new Event();
event.loadById(req.params.id)
.then(() => {
event.enroll(user, roleId);
})
.catch(() => {
res.status(404).json(Response(true, {}, Constants.EVENT_NOT_FOUND_MSG));
});
});

/**
* Returns a event by ID
* @param id event id to search for
* @return event if found
*
* @MissingTests
*/
eventRouter.get('/:id', (req, res) => {
const fields = (req.query.fields) ? req.query.fields : 'name,subtitle,eventPeriod,enrollmentPeriod,location,published';
Expand All @@ -58,7 +97,7 @@ eventRouter.get('/:id', (req, res) => {
res.json(Response(false, event.toFormatedEvent(fields)));
})
.catch(() => {
res.json(Response(true, {}, 'Não existe evento com este ID'));
res.status(404).json(Response(true, {}, Constants.EVENT_NOT_FOUND_MSG));
});
});

Expand Down
2 changes: 2 additions & 0 deletions src/controllers/event/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const EVENT_NOT_FOUND_MSG = 'O evento não existe';
export const EVENT_CREATION_ERROR_MSG = 'Erro ao criar evento';

0 comments on commit 09af074

Please sign in to comment.