24. Leave group

Now we need to have the ability for the users to leave the group. We already have a button that says “Leave group” if the user has accepted the invitation from the previous article. We just need to create a method that will call the AJAX request to the server.

The following code goes in your GroupsComponent.vue file methods object.

leaveGroup: function () {
	// get vue instance
	const self = this

	// create form data object
	const form = event.target
	const _id = form._id.value
	const formData = new FormData(form)

	// ask for user confirmation
	swal.fire({
		title: 'Leave group',
		text: "Are you sure you want to leave this group ?",
		icon: 'warning',
		showCancelButton: true,
		confirmButtonColor: '#3085d6',
		cancelButtonColor: '#d33',
		confirmButtonText: 'Yes'
	}).then(async function (result) {
		if (result.isConfirmed) {
			
			// call an AJAX
			const response = await axios.post(
                self.$apiURL + "/groups/leaveGroup",
                formData,
                {
                    headers: self.$headers
                }
            )

            if (response.data.status == "success") {
            	// remove the group from local array
            	const groups = store.getters.getGroups
            	for (let a = 0; a < groups.length; a++) {
            		if (groups[a]._id == _id) {
            			groups.splice(a, 1)
            			break
            		}
            	}
            	store.commit("setGroups", groups)

            	swal.fire("Leave group", response.data.message, "success")
            } else {
                swal.fire("Error", response.data.message, "error")
            }

		}
	})
},

This will first ask for confirmation as we did for joining the group. If the user confirms it, then it will send an AJAX to the server. After the response is received, we will check if the response status is “success”. If yes, then we will simply remove the group from the local array.

Now we need to create an API that will handle this request. The following code goes in the api/modules/groups.js file:

router.post("/leaveGroup", auth, async function (request, result) {
    // get logged-in users
    const user = request.user;

    // get unique ID of group
    const _id = request.fields._id;

    // check if group exists
    const group = await db.collection("groups").findOne({
        "_id": ObjectId(_id)
    });

    if (group == null) {
        result.json({
            status: "error",
            message: "Group does not exists."
        });
        return;
    }

    // check if you are an admin
    if (group.createdBy._id.toString() == user._id.toString()) {
        result.json({
            status: "error",
            message: "Sorry, you are an admin. Please make anyone else the admin before leaving."
        });
        return;
    }

    // check if you are a member
    let isMember = false;
    for (let a = 0; a < group.members.length; a++) {
        if (group.members[a].user._id.toString() == user._id.toString()) {
            isMember = true;
            break;
        }
    }

    if (!isMember) {
        result.json({
            status: "error",
            message: "Sorry, you are not a member of this group."
        });
        return;
    }

    // remove yourself as member from groups collection
    await db.collection("groups").findOneAndUpdate({
        _id: group._id
    }, {
        $pull: {
            members: {
                "user._id": user._id
            }
        }
    });

    // send the response back to client
    result.json({
        status: "success",
        message: "Group has been left."
    });
});

This will first check if the group exists. Then it will check if the person leaving the group is an admin. If he is an admin, then we will show him an error saying that he must give any other member of the group “admin” privileges before leaving the group. This is necessary because when an admin leaves, he must give someone else his role to manage the group. We will add this feature later in this series.

If he is not an admin, then we will check if he is a member of the group. If he is a member of the group, then we will finally remove him from the “members” array of groups collection. We are using the Mongo DB $pull operator for this purpose, you can learn more about this from here. And send the response back to the client.





Please disable your adblocker or whitelist this site!