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()
:
jsrouter.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
:
jsconst 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:
js9123const 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:
js912345if (!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:
js912345try {// ... (code for retrieving and processing data)} catch (error) {console.error(error.message);}
Complete code of the postsRoutes.js file at this step
js99123456789101112131415161718192021222324252627282930313233343536const express = require("express");const fs = require("fs/promises");const validatePostData = require("../middlewares/validateData");const router = express.Router();// Function to read data from the JSON fileasync function readData() {try {// Read the contents of the `posts.json` fileconst data = await fs.readFile("./database/posts.json");// Parse the JSON data into a JavaScript objectreturn JSON.parse(data);} catch (error) {// If an error occurs during reading or parsing, throw the errorthrow error;}}// GET ALL POSTSrouter.get("/", async (req, res, next) => {try {// Call the `readData` function to retrieve the list of postsconst data = await readData();// Send the retrieved data as the responseres.status(200).send(data);} catch (error) {// If an error occurs during data retrieval or sending the responseconsole.error(error.message); // Log the error to the console for debugging}});// GET POST BY IDrouter.get("/post/:id", async (req, res, next) => {try {// Extract the post ID from the request parameters
Tak for dine kommentarer!
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat