Course Content
Backend Development with Node.js and Express.js
Backend Development with Node.js and Express.js
Building the UPDATE Post by Id Endpoint
We will research how to update an existing post using the "UPDATE POST BY ID" route within the postsRoutes.js
file. This route handles the updating of a post based on its unique ID.
Route Definition
The code below defines the "UPDATE POST BY ID" route using router.put()
:
router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
- This route is configured to handle HTTP PUT requests, specifically for updating posts;
- It includes a parameterized
:id
in the route path to identify the post to be updated; - The
validatePostData
middleware is added to ensure data validation before proceeding. The logic of thevalidatePostData
middleware remains the same as in the previous step.
Obtaining Data from the Request
Here, we extract the necessary data from the request, including the post ID and the updated post content:
const postId = req.params.id;
const updatedData = {
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
- The post ID is extracted from the request parameters, making it available for further processing. The
:id
parameter from the route URL is captured usingreq.params.id
; - The
username
,postTitle
, andpostContent
are extracted from the request body.
Update the Post in the Database
Updating an existing post involves several steps, as outlined below:
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[postIndex] = {
...data[postIndex],
...updatedData,
};
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- We read the existing data from the JSON file using the asynchronous
readData
function, as explained earlier; - The
postIndex
variable stores the index of the post to be updated in thedata
array by comparing post IDs; - If the post is not found (i.e.,
postIndex === -1
), a 404 (Not Found) response with an error message is returned to the client; - To update the post data, we merge the existing post data (
...data[postIndex]
) with the updated data (...updatedData
). This ensures that only the specified fields are updated and existing data is retained; - Finally, the updated
data
array is written back to the JSON file to save the changes made to the post.
Sending a Response
Upon successful post update, a JSON response is sent to the client. The response includes a status code of 200 (OK), indicating a successful update and the updated post data.
res.status(200).json(data[postIndex]);
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
const postId = req.params.id;
// Read data from the JSON file
const data = await readData();
// Find the post with the matching ID
const post = data.find((post) => post.id === postId);
// If the post is not found, send a 404 response
if (!post) {
res.status(404).json({ error: "Post not found" });
} else {
// If the post is found, send it as the response
res.status(200).send(post);
}
} catch (error) {
// Handle errors by logging them and sending an error response
console.error(error.message);
}
});
// CREATE POST
router.post("/", validatePostData, async (req, res, next) => {
try {
const newPost = {
id: Date.now().toString(), // Generate a unique ID for the new post
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
// Read the existing data
const data = await readData();
// Add the new post to the data
data.push(newPost);
// Write the updated data back to the JSON file
await fs.writeFile("./database/posts.json", JSON.stringify(data));
// Send a success response with the new post
res.status(201).json(newPost);
} catch (error) {
// Handle errors by logging them to the console
console.error(error.message);
}
});
// UPDATE POST BY ID
router.put("/post/:id", validatePostData, async (req, res, next) => {
try {
// Extract the post ID from the request parameters
const postId = req.params.id;
// Extract the updated data from the request body
const updatedData = {
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
// Read the existing data
const data = await readData();
// Find the index of the post with the specified ID in the data array
const postIndex = data.findIndex((post) => post.id === postId);
// If the post with the specified ID doesn't exist, return a 404 error
if (postIndex === -1) {
return res.status(404).json({ error: "Post not found" });
}
// Update the post data with the new data using spread syntax
data[postIndex] = {
...data[postIndex], // Keep existing data
...updatedData, // Apply updated data
};
// Write the updated data back
await fs.writeFile("./database/posts.json", JSON.stringify(data));
// Send a success response with the updated post
res.status(200).json(data[postIndex]);
} catch (error) {
console.error(error.message);
next(error);
}
});
Thanks for your feedback!