Skip to content

Commit

Permalink
created join group controller
Browse files Browse the repository at this point in the history
  • Loading branch information
abhiraj-ku committed Sep 12, 2024
1 parent 53e9e6e commit 6e5731a
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
52 changes: 51 additions & 1 deletion src/controllers/groupController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,54 @@ const groupModel = require("../models/groupModel");
module.exports.createGroup = async (req, res) => {};

// TODO: implement the join group func wrt to frontend design
module.exports.joinGroup = async (req, res) => {};
module.exports.joinGroup = async (req, res) => {
const { groupName, groupCode } = req.body;

try {
// Validate input data
if (!groupCode || !groupName) {
return res.status(400).json({
message: "Missing required fields",
});
}
// Find group by name and code
const group = await groupModel.findOne({
$where: {
groupName: groupName,
groupCode: groupCode,
},
});

if (!group) {
return res
.status(404)
.json({ message: "Group code or group name is invalid" });
}

// Check if user is already part of the group
const isMember = group.members.some((member) =>
member.user.equals(req.user.id)
);

if (isMember) {
return res
.status(400)
.json({ message: "You are already a part of this group" });
}

// Add the user to the group
group.members.push({ user: req.user.id });
await group.save();

// Return a success message
return res.status(200).json({
message: "You have successfully joined the group",
});
return;
} catch (error) {
console.error(error);
return res
.status(500)
.json({ error: "An error occurred while joining the group" });
}
};
7 changes: 6 additions & 1 deletion src/models/groupModel.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const mongoose = require("mongoose");

const groupSchema = new mongoose.Schema({
name: {
groupName: {
type: String,
required: true,
trim: true,
Expand All @@ -10,6 +10,11 @@ const groupSchema = new mongoose.Schema({
type: String,
trim: true,
},
groupCode: {
type: String,
required: true,
unique: true,
},
members: [
{
user: {
Expand Down

0 comments on commit 6e5731a

Please sign in to comment.