Adding a controller handler

Now that we have added a new route, we need to create the controller function that it's using as its callback (image.remove). Edit controllers/image.js and add the following new function code after the existing comment: function(req, res){} operation (don't forget to add a trailing comma after the comment function, since you are adding a new function):

remove: (req, res) => {
Models.Image.findOne({
filename: { $regex: req.params.image_id }
},
(err, image) => {
if (err) { throw err; }

fs.unlink(path.resolve(`./public/upload/${image.filename}`),
(err) => {
if (err) { throw err; }

Models.Comment.remove({ image_id: image._id },
(err) => {
image.remove((err) => {
if (!err) {
res.json(true);
} else {
res.json(false);
}
});
});
});
});
}

This function performs four primary functions (and as such, nests four layers deep with callbacks--we could have used the async's series method here to prevent the crazy amount of nesting). The first task is to find the image that we are attempting to remove. Once that image is found, the file associated with the image should be deleted. Next, find the comments associated with the image and remove them. Once they have been removed, the last step is to remove the image itself. Assuming all of that was a success, simply send a true Boolean JSON response back to the browser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.236.70