Conteúdo do Curso
Backend Development with Node.js and Express.js
Backend Development with Node.js and Express.js
Building the GET Post by Id Endpoint
We will explore implementing the "GET POST BY ID" route within the postsRoutes.js file
. This route fetches and returns a specific post based on its unique identifier (id
) provided as part of the URL.
Note
The term 'database' specifically pertains to the
posts.json
file located in thedatabase
folder.
Route Definition
The code below defines the "GET POST BY ID" route using router.get()
:
router.get("/post/:id", async (req, res, next) => { ... }
- This route is configured to handle HTTP GET requests;
- The route path
/post/:id
includes a parameter:id
, which captures the post ID from the URL.
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, making it available for further processing.
Finding the Post in the Database
Next, we search for the post with the matching ID in the database:
const data = await readData();
const post = data.find((post) => post.id === postId);
- We use the asynchronous
readData
function to retrieve data from the JSON file; - The
find()
method is employed to locate a post with a matching ID within the retrieved data; - The
post
variable holds the found post orundefined
if no match is found.
Handling the Response
We handle the response based on whether a post was found or not:
if (!post) {
res.status(404).json({ error: "Post not found" });
} else {
res.status(200).send(post);
}
- If no post was found (i.e.,
post
isundefined
), we send a 404 response along with an error message, indicating that the requested post was not found; - If a post was found, we send the post as the response with a status code of 200 (OK).
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);
}
});
Obrigado pelo seu feedback!