Skip to content

Commit

Permalink
Allow to remove threads
Browse files Browse the repository at this point in the history
  • Loading branch information
peter-hank committed Jul 19, 2021
1 parent f838e1d commit 0791245
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/config/roles.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const allRoles = {
'getThread',
'publicTopics',
'publicThreads',
'deleteThread',
],
admin: ['getUsers', 'manageUsers'],
};
Expand Down
11 changes: 11 additions & 0 deletions src/controllers/thread.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,22 @@ const allPublic = catchAsync(async (req, res) => {
res.status(httpStatus.OK).send(threads);
});

const deleteThread = catchAsync(async (req, res) => {
const thread = await threadService.deleteThread(req.params.threadId, req.user, res);

if (thread.errorCode) {
return res.status(thread.errorCode).send(thread.message);
}

res.status(httpStatus.OK).send(thread);
});

module.exports = {
createThread,
userThreads,
getThread,
getTopicThreads,
follow,
allPublic,
deleteThread,
};
1 change: 1 addition & 0 deletions src/routes/v1/threads.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ router.route('/userThreads').get(auth('userThreads'), threadsController.userThre
router.route('/:threadId').get(auth('getThread'), threadsController.getThread);
router.route('/topic/:topicId').get(threadsController.getTopicThreads);
router.route('/follow').post(auth('followThread'), threadsController.follow);
router.route('/deleteThread/:threadId').delete(auth('deleteThread'), threadsController.deleteThread);

module.exports = router;
21 changes: 20 additions & 1 deletion src/services/thread.service.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const mongoose = require('mongoose');
const { Thread, Topic, Follower } = require('../models');
const { Thread, Topic, Follower, Message } = require('../models');
const httpStatus = require('http-status');

/**
* Create a thread
Expand Down Expand Up @@ -62,6 +63,23 @@ const allPublic = async () => {
return threads;
};

const deleteThread = async (id, user) => {
const thread = await Thread.findOne({ _id: id }).select('name slug owner').exec();

if (user._id.toString() !== thread.owner.toString()) {
return {
errorCode: httpStatus.UNAUTHORIZED,
message: "You're not the owner of this thread",
};
}

await Thread.deleteOne({ _id: id });
await Follower.deleteMany({ thread });
await Message.deleteMany({ thread });

return thread;
};

module.exports = {
createThread,
userThreads,
Expand All @@ -70,4 +88,5 @@ module.exports = {
follow,
findByIdFull,
allPublic,
deleteThread,
};

0 comments on commit 0791245

Please sign in to comment.