The delete course API

In order to implement a backend API that takes a request to delete a specified course from the database, we will first define a DELETE route as shown in the following code.

mern-classroom/server/routes/course.routes.js:

router.route('/api/courses/:courseId')
.delete(authCtrl.requireSignin, courseCtrl.isInstructor,
courseCtrl.remove)

This DELETE route takes the course ID as a URL parameter and checks if the current user is signed in and authorized to perform this delete, before proceeding to the remove controller method, which is defined in the following code.

mern-classroom/server/controllers/course.controller.js:

const remove = async (req, res) => {
try {
let course = req.course
let deleteCourse = await course.remove()
res.json(deleteCourse)
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
}

The remove method simply deletes the course document that corresponds to the provided ID from the Courses collection in the database. To access this backend API in the frontend, you will also need a fetch method with this route; similar to other API implementations. The fetch method will need to take the course ID and current user's auth credentials, then call the delete API with these values.

The fetch method will be used when the user performs the delete operation by clicking a button on the interface. In the next section, we will discuss a React component called DeleteCourse, which is where this interaction will take place.

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

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