Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Implementing the "DELETE POST BY ID" Route | Developing REST API
Backend Development with Node.js and Express.js

book
Implementing the "DELETE POST BY ID" Route

We'll dive into the implementation of the "DELETE POST BY ID" route within the postsRoutes.js file. This route allows clients to delete a specific post by providing its unique ID.

Route Definition

The code below defines the "DELETE POST BY ID" route using router.delete():

router.delete("/post/:id", async (req, res, next) => { ... }

This route handles HTTP DELETE requests with a parameterized :id in the route path. The :id parameter is used to identify the post to be deleted. We don't need extra middleware like dataValidation as we get all the necessary information from the URL parameter.

Extracting the Post ID

We extract the post ID from the request parameters using req.params.id:

const postId = req.params.id;

This line captures the :id value from the URL, allowing us to work with it in the subsequent code.

Delete the Post

Here's how we delete the post:

const data = await readData();

const postIndex = data.findIndex((post) => post.id === postId);

if (postIndex === -1) {
return res.status(404).json({ error: "Post not found" });
}

data.splice(postIndex, 1);

await fs.writeFile("./database/posts.json", JSON.stringify(data));
  • We begin by reading the existing data from the JSON file using the asynchronous readData function, as explained earlier.
  • We find the index of the post to delete in the data array by comparing post IDs.
  • If the post is not found (i.e., postIndex === -1), we return a 404 (Not Found) response with an error message.
  • Using the splice method, we remove the post data from the data array. The postIndex variable determines the position of the post to delete.
  • The updated data array, with the post removed, is then written back to the JSON file to save the changes made during the deletion.

Sending a Response

A JSON response with a status code of 200 (OK) is sent to the client, indicating a successful deletion. The response includes a message confirming that the post was deleted successfully:

res.status(200).json({ message: "Post deleted successfully" });

Error Handling

We wrap the route code in a try-catch block to handle potential errors during data retrieval or request processing. Any errors that occur are logged to the console for debugging purposes:

try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}

Complete code of the postsRoutes.js file at this step

const express = require("express");
const fs = require("fs/promises");
const validatePostData = require("../middlewares/validateData");

const router = express.Router();

// Function to read data from the JSON file
async function readData() {
try {
// Read the contents of the `posts.json` file
const data = await fs.readFile("./database/posts.json");
// Parse the JSON data into a JavaScript object
return JSON.parse(data);
} catch (error) {
// If an error occurs during reading or parsing, throw the error
throw error;
}
}

// GET ALL POSTS
router.get("/", async (req, res, next) => {
try {
// Call the `readData` function to retrieve the list of posts
const data = await readData();
// Send the retrieved data as the response
res.status(200).send(data);
} catch (error) {
// If an error occurs during data retrieval or sending the response
console.error(error.message); // Log the error to the console for debugging
}
});

// GET POST BY ID
router.get("/post/:id", async (req, res, next) => {
try {
// Extract the post ID from the request parameters

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 9
some-alt