Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Creazione dell'Endpoint GET Post per ID | Creazione di API REST con Node.js ed Express.js
Sviluppo Backend con Node.js ed Express.js

Creazione dell'Endpoint GET Post per ID

Scorri per mostrare il menu

Esplorazione dell'implementazione della rotta "GET POST BY ID" all'interno del file postsRoutes.js file. Questa rotta recupera e restituisce un post specifico in base al suo identificatore univoco (id) fornito come parte dell'URL.

Note
Nota

Il termine 'database' si riferisce specificamente al file posts.json situato nella cartella database.

Definizione della rotta

Il codice seguente definisce la rotta "GET POST BY ID" utilizzando router.get():

router.get("/post/:id", async (req, res, next) => { ... }
  • Questa rotta è configurata per gestire richieste HTTP GET;
  • Il percorso della rotta /post/:id include un parametro :id, che acquisisce l'ID del post dall'URL.

Estrazione dell'ID del post

Estrazione dell'ID del post dai parametri della richiesta utilizzando req.params.id:

const postId = req.params.id;

Questa riga cattura il valore :id dall'URL, rendendolo disponibile per l'elaborazione successiva.

Ricerca del post nel database

Successivamente, ricerca del post con l'ID corrispondente nel database:

const data = await readData();

const post = data.find((post) => post.id === postId);
  • Utilizzo della funzione asincrona readData per recuperare i dati dal file JSON;
  • Il metodo find() viene impiegato per individuare un post con ID corrispondente all'interno dei dati recuperati;
  • La variabile post contiene il post trovato oppure undefined se non viene trovato alcun corrispondenza.

Gestione della risposta

Gestione della risposta in base al fatto che il post sia stato trovato o meno:

if (!post) {
  res.status(404).json({ error: "Post not found" });
} else {
  res.status(200).send(post);
}
  • Se il post non viene trovato (cioè post è undefined), invio di una risposta 404 insieme a un messaggio di errore, indicando che il post richiesto non è stato trovato;
  • Se il post viene trovato, invio del post come risposta con codice di stato 200 (OK).

Gestione degli errori

Il codice della route viene racchiuso in un blocco try-catch per gestire eventuali errori durante il recupero dei dati o l'elaborazione della richiesta. Qualsiasi errore che si verifica viene registrato nella console per scopi di debug:

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

Codice completo del file postsRoutes.js in questo passaggio

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);
  }
});
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 6

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Creazione dell'Endpoint GET Post per ID

Esplorazione dell'implementazione della rotta "GET POST BY ID" all'interno del file postsRoutes.js file. Questa rotta recupera e restituisce un post specifico in base al suo identificatore univoco (id) fornito come parte dell'URL.

Note
Nota

Il termine 'database' si riferisce specificamente al file posts.json situato nella cartella database.

Definizione della rotta

Il codice seguente definisce la rotta "GET POST BY ID" utilizzando router.get():

router.get("/post/:id", async (req, res, next) => { ... }
  • Questa rotta è configurata per gestire richieste HTTP GET;
  • Il percorso della rotta /post/:id include un parametro :id, che acquisisce l'ID del post dall'URL.

Estrazione dell'ID del post

Estrazione dell'ID del post dai parametri della richiesta utilizzando req.params.id:

const postId = req.params.id;

Questa riga cattura il valore :id dall'URL, rendendolo disponibile per l'elaborazione successiva.

Ricerca del post nel database

Successivamente, ricerca del post con l'ID corrispondente nel database:

const data = await readData();

const post = data.find((post) => post.id === postId);
  • Utilizzo della funzione asincrona readData per recuperare i dati dal file JSON;
  • Il metodo find() viene impiegato per individuare un post con ID corrispondente all'interno dei dati recuperati;
  • La variabile post contiene il post trovato oppure undefined se non viene trovato alcun corrispondenza.

Gestione della risposta

Gestione della risposta in base al fatto che il post sia stato trovato o meno:

if (!post) {
  res.status(404).json({ error: "Post not found" });
} else {
  res.status(200).send(post);
}
  • Se il post non viene trovato (cioè post è undefined), invio di una risposta 404 insieme a un messaggio di errore, indicando che il post richiesto non è stato trovato;
  • Se il post viene trovato, invio del post come risposta con codice di stato 200 (OK).

Gestione degli errori

Il codice della route viene racchiuso in un blocco try-catch per gestire eventuali errori durante il recupero dei dati o l'elaborazione della richiesta. Qualsiasi errore che si verifica viene registrato nella console per scopi di debug:

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

Codice completo del file postsRoutes.js in questo passaggio

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);
  }
});
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 6
some-alt