Skip to content

Commit

Permalink
Merge pull request #91 from hatchways/BE-chat-controller-67
Browse files Browse the repository at this point in the history
Chat Controller #67
  • Loading branch information
timegambit authored Feb 4, 2021
2 parents 3c6b913 + a74b3e1 commit 7ab0985
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 51 deletions.
2 changes: 1 addition & 1 deletion client/src/context/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const fetchProfile = () => async dispatch => {
});
return user.groups;
} catch (err) {
if (err.response.status === 401) {
if (err.response && err.response.status === 401) {
dispatch({ type: 'LOGIN_FAIL' });
}
console.log(err.message);
Expand Down
1 change: 1 addition & 0 deletions client/src/context/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export const initialState = {
isAuth: false,
userCourse: {},
profile: {},
userGroups: {groups: [], courseGroups: []},
isOpen: false,
};

Expand Down
72 changes: 71 additions & 1 deletion server/controllers/user.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,77 @@
const { GeneralError, NotFound, Unauthorized } = require('../utils/errors');
const bcrypt = require('bcrypt');
const { validationResult } = require('express-validator');
const Conversation = require('../models/Conversation');
const Course = require('../models/courses');
const Group = require('../models/Group');
const User = require('../models/user');
const { GeneralError, NotFound, Unauthorized } = require('../utils/errors');

//TODO move rest of functions from user routes here

exports.createGroup = async (req, res, next) => {
const userId = req.body.userId;
const imageUrl = req.body.imageUrl;
const courseId = req.body.courseId;
const groupName = req.body.groupName.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase());

const session = await Group.startSession();
session.startTransaction();

try {

const instance = (await Group.create([{
name: groupName,
members: [userId],
image: imageUrl,
course: courseId,
admin: userId
}], {session}))[0];

await Conversation.create([{ group: instance._id }], { session });

await User.findByIdAndUpdate(userId, { $addToSet: { groups: instance._id } }, { useFindAndModify: false, new: true })
.session(session)
.catch(() => {
throw new GeneralError('Error updating User Groups');
});

await Course.findByIdAndUpdate(courseId, { $addToSet: { groups: instance._id } }, { useFindAndModify: false, new: true })
.session(session)
.catch(() => {
throw new GeneralError('Error updating Course Groups');
});

await session.commitTransaction();
session.endSession();
res.status(201);
res.send({
data: instance
});

} catch(err) {
console.log(err)
await session.abortTransaction();
session.endSession();
next(err);
}
};

exports.getConversations = async (req, res, next) => {

try {
const user = await User.findById(req.body.userId);
if (!user) throw new NotFound('No user found');

const {groups} = user;
const convos = await Conversation.find({ 'group': {$in: groups }});
if (!convos) throw new GeneralError('Error finding conversations');

res.status(200).json(convos);
} catch(err) {
console.log(err);
next(err);
}
};

exports.passwordChange = async (req, res, next) => {
const errors = validationResult(req);
Expand Down
58 changes: 9 additions & 49 deletions server/routes/user.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const express = require('express');
const router = express.Router();
const userController = require('../controllers/user');
const verifyAuth = require('../middleware/verifyAuth');
const User = require('../models/user');
const University = require('../models/universities');
const { BadRequest, GeneralError } = require('../utils/errors');
const Group = require('../models/Group');
const Course = require('../models/courses');
require('../models/courses');

// Get the logged in user
router.get('/', verifyAuth, async function (req, res, next) {
Expand Down Expand Up @@ -233,54 +234,9 @@ router.post('/groups/:groupId', verifyAuth, async function (req, res, next) {
}
});

// create a new group from a course they are enrolled in
router.post('/groups', verifyAuth, async function (req, res, next) {

const userId = req.body.userId;
const imageUrl = req.body.imageUrl;
const courseId = req.body.courseId;
const groupName = req.body.groupName.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase());

const session = await Group.startSession();
session.startTransaction();

try {

const instance = (await Group.create([{
name: groupName,
members: [userId],
image: imageUrl,
course: courseId,
admin: userId
}], {session}))[0];

const userUpdate = await User.findByIdAndUpdate(userId, { $addToSet: { groups: instance._id } }, { useFindAndModify: false, new: true })
.session(session)
.catch((err) => {
throw new GeneralError('Error updating User Groups');
});

const courseUpdate = await Course.findByIdAndUpdate(courseId, { $addToSet: { groups: instance._id } }, { useFindAndModify: false, new: true })
.session(session)
.catch((err) => {
throw new GeneralError('Error updating Course Groups');
});

await session.commitTransaction();
session.endSession();
res.status(201);
res.send({
data: instance
});

} catch(err) {
console.log(err)
await session.abortTransaction();
session.endSession();
next(err);
}

});
// POST user/groups
// Creates a new group from a users course
router.post('/groups', verifyAuth, userController.createGroup);

// delete a user from a group
router.delete('/groups/:groupId', verifyAuth, async function (req, res, next) {
Expand Down Expand Up @@ -318,4 +274,8 @@ router.delete('/groups/:groupId', verifyAuth, async function (req, res, next) {
}
});

// GET user/conversations
// Finds all the conversations of all the users groups
router.get('/conversations', verifyAuth, userController.getConversations);

module.exports = router;

0 comments on commit 7ab0985

Please sign in to comment.