Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Building the GET Post by Id Endpoint | Building REST APIs with Node.js and Express.js
Backend Development with Node.js and Express.js
course content

Conteúdo do Curso

Backend Development with Node.js and Express.js

Backend Development with Node.js and Express.js

1. Introduction to Node.js and Backend Development
2. Building Console Applications with Node.js
3. Developing Web Applications with Express.js
4. Building REST APIs with Node.js and Express.js

book
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 the database 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 or undefined 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 is undefined), 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);
  }
});

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 6

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

course content

Conteúdo do Curso

Backend Development with Node.js and Express.js

Backend Development with Node.js and Express.js

1. Introduction to Node.js and Backend Development
2. Building Console Applications with Node.js
3. Developing Web Applications with Express.js
4. Building REST APIs with Node.js and Express.js

book
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 the database 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 or undefined 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 is undefined), 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);
  }
});

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 6
some-alt