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

bookCreazione dell'Endpoint Update Post per Id

Analisi del processo di aggiornamento di un post esistente utilizzando la rotta "UPDATE POST BY ID" all'interno del file postsRoutes.js. Questa rotta gestisce l'aggiornamento di un post in base al suo ID univoco.

Definizione della rotta

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

router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
  • Questa rotta è configurata per gestire richieste HTTP PUT, specificamente per l'aggiornamento dei post;
  • Include un parametro :id nel percorso della rotta per identificare il post da aggiornare;
  • Il middleware validatePostData viene aggiunto per garantire la validazione dei dati prima di procedere. La logica del middleware validatePostData rimane invariata rispetto al passaggio precedente.

Ottenere i dati dalla richiesta

In questa fase, vengono estratti i dati necessari dalla richiesta, inclusi l'ID del post e il contenuto aggiornato del post:

const postId = req.params.id;
const updatedData = {
  username: req.body.username,
  postTitle: req.body.postTitle,
  postContent: req.body.postContent,
};
  • L'ID del post viene estratto dai parametri della richiesta, rendendolo disponibile per l'elaborazione successiva. Il parametro :id dall'URL della rotta viene acquisito tramite req.params.id;
  • username, postTitle e postContent vengono estratti dal corpo della richiesta.

Aggiornare il post nel database

L'aggiornamento di un post esistente prevede diversi passaggi, illustrati di seguito:

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));
  • I dati esistenti vengono letti dal file JSON utilizzando la funzione asincrona readData, come spiegato in precedenza;
  • La variabile postIndex memorizza l'indice del post da aggiornare nell'array data confrontando gli ID dei post;
  • Se il post non viene trovato (ovvero postIndex === -1), viene restituita al client una risposta 404 (Not Found) con un messaggio di errore;
  • Per aggiornare i dati del post, si uniscono i dati esistenti del post (...data[postIndex]) con i dati aggiornati (...updatedData). Questo garantisce che vengano aggiornati solo i campi specificati e che i dati esistenti vengano mantenuti;
  • Infine, l'array data aggiornato viene riscritto nel file JSON per salvare le modifiche apportate al post.

Invio della risposta

Dopo l'aggiornamento riuscito del post, viene inviata una risposta JSON al client. La risposta include un codice di stato 200 (OK), che indica l'avvenuto aggiornamento e i dati aggiornati del post.

res.status(200).json(data[postIndex]);

Gestione degli errori

Il codice della route viene racchiuso in un blocco try-catch per gestire potenziali errori durante il recupero dei dati o l'elaborazione della richiesta. Eventuali errori che si verificano vengono registrati 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);
  }
});

// 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);
  }
});

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 8

Chieda ad AI

expand

Chieda ad AI

ChatGPT

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

Awesome!

Completion rate improved to 2.56

bookCreazione dell'Endpoint Update Post per Id

Scorri per mostrare il menu

Analisi del processo di aggiornamento di un post esistente utilizzando la rotta "UPDATE POST BY ID" all'interno del file postsRoutes.js. Questa rotta gestisce l'aggiornamento di un post in base al suo ID univoco.

Definizione della rotta

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

router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
  • Questa rotta è configurata per gestire richieste HTTP PUT, specificamente per l'aggiornamento dei post;
  • Include un parametro :id nel percorso della rotta per identificare il post da aggiornare;
  • Il middleware validatePostData viene aggiunto per garantire la validazione dei dati prima di procedere. La logica del middleware validatePostData rimane invariata rispetto al passaggio precedente.

Ottenere i dati dalla richiesta

In questa fase, vengono estratti i dati necessari dalla richiesta, inclusi l'ID del post e il contenuto aggiornato del post:

const postId = req.params.id;
const updatedData = {
  username: req.body.username,
  postTitle: req.body.postTitle,
  postContent: req.body.postContent,
};
  • L'ID del post viene estratto dai parametri della richiesta, rendendolo disponibile per l'elaborazione successiva. Il parametro :id dall'URL della rotta viene acquisito tramite req.params.id;
  • username, postTitle e postContent vengono estratti dal corpo della richiesta.

Aggiornare il post nel database

L'aggiornamento di un post esistente prevede diversi passaggi, illustrati di seguito:

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));
  • I dati esistenti vengono letti dal file JSON utilizzando la funzione asincrona readData, come spiegato in precedenza;
  • La variabile postIndex memorizza l'indice del post da aggiornare nell'array data confrontando gli ID dei post;
  • Se il post non viene trovato (ovvero postIndex === -1), viene restituita al client una risposta 404 (Not Found) con un messaggio di errore;
  • Per aggiornare i dati del post, si uniscono i dati esistenti del post (...data[postIndex]) con i dati aggiornati (...updatedData). Questo garantisce che vengano aggiornati solo i campi specificati e che i dati esistenti vengano mantenuti;
  • Infine, l'array data aggiornato viene riscritto nel file JSON per salvare le modifiche apportate al post.

Invio della risposta

Dopo l'aggiornamento riuscito del post, viene inviata una risposta JSON al client. La risposta include un codice di stato 200 (OK), che indica l'avvenuto aggiornamento e i dati aggiornati del post.

res.status(200).json(data[postIndex]);

Gestione degli errori

Il codice della route viene racchiuso in un blocco try-catch per gestire potenziali errori durante il recupero dei dati o l'elaborazione della richiesta. Eventuali errori che si verificano vengono registrati 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);
  }
});

// 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);
  }
});

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 8
some-alt