Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Implémentation de la Route "Delete Post by ID" | Développement d'API REST
Développement Backend Avec Node.js et Express.js
course content

Contenu du cours

Développement Backend Avec Node.js et Express.js

Développement Backend Avec Node.js et Express.js

1. Introduction
2. Applications Console
3. Cadre Express.js
4. Développement d'API REST

book
Implémentation de la Route "Delete Post by ID"

Nous allons plonger dans l'implémentation de la route "DELETE POST BY ID" dans le fichier postsRoutes.js. Cette route permet aux clients de supprimer un post spécifique en fournissant son ID unique.

Définition de la Route

Le code ci-dessous définit la route "DELETE POST BY ID" en utilisant router.delete():

router.delete("/post/:id", async (req, res, next) => { ... }

Cette route gère les requêtes HTTP DELETE avec un :id paramétré dans le chemin de la route. Le paramètre :id est utilisé pour identifier le post à supprimer. Nous n'avons pas besoin de middleware supplémentaire comme dataValidation car nous obtenons toutes les informations nécessaires à partir du paramètre URL.

Extraction de l'ID du Post

Nous extrayons l'ID du post à partir des paramètres de la requête en utilisant req.params.id:

const postId = req.params.id;

Cette ligne capture la valeur :id de l'URL, nous permettant de travailler avec dans le code suivant.

Supprimer le Post

Voici comment nous supprimons le post :

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.splice(postIndex, 1);

await fs.writeFile("./database/posts.json", JSON.stringify(data));
  • Nous commençons par lire les données existantes à partir du fichier JSON en utilisant la fonction asynchrone readData, comme expliqué précédemment.
  • Nous trouvons l'index du post à supprimer dans le tableau data en comparant les IDs des posts.
  • Si le post n'est pas trouvé (c'est-à-dire, postIndex === -1), nous retournons une réponse 404 (Non Trouvé) avec un message d'erreur.
  • En utilisant la méthode splice, nous supprimons les données du post du tableau data. La variable postIndex détermine la position du post à supprimer.
  • Le tableau data mis à jour, avec le post supprimé, est ensuite réécrit dans le fichier JSON pour enregistrer les modifications effectuées lors de la suppression.

Envoi d'une Réponse

Une réponse JSON avec un code de statut 200 (OK) est envoyée au client, indiquant une suppression réussie. La réponse inclut un message confirmant que le post a été supprimé avec succès :

res.status(200).json({ message: "Post deleted successfully" });

Gestion des Erreurs

Nous enveloppons le code de la route dans un bloc try-catch pour gérer les erreurs potentielles lors de la récupération des données ou du traitement de la requête. Toutes les erreurs qui se produisent sont enregistrées dans la console à des fins de débogage :

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

Code complet du fichier postsRoutes.js à cette étape

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

// DELETE POST BY ID
router.delete("/post/:id", async (req, res, next) => {
  try {
    // Extract the post ID from the request parameters
    const postId = req.params.id;

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

    // Remove the post from the data array using `splice`
    data.splice(postIndex, 1);

    // Write the updated data back to the data source (e.g., a JSON file)
    await fs.writeFile("./database/posts.json", JSON.stringify(data));

    // Send a success response with the JSON response indicating successful deletion
    res.status(200).json({ message: "Post deleted successfully" });
  } catch (error) {
    console.error(error.message);
    next(error);
  }
});

module.exports = router;

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 4. Chapitre 9

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

course content

Contenu du cours

Développement Backend Avec Node.js et Express.js

Développement Backend Avec Node.js et Express.js

1. Introduction
2. Applications Console
3. Cadre Express.js
4. Développement d'API REST

book
Implémentation de la Route "Delete Post by ID"

Nous allons plonger dans l'implémentation de la route "DELETE POST BY ID" dans le fichier postsRoutes.js. Cette route permet aux clients de supprimer un post spécifique en fournissant son ID unique.

Définition de la Route

Le code ci-dessous définit la route "DELETE POST BY ID" en utilisant router.delete():

router.delete("/post/:id", async (req, res, next) => { ... }

Cette route gère les requêtes HTTP DELETE avec un :id paramétré dans le chemin de la route. Le paramètre :id est utilisé pour identifier le post à supprimer. Nous n'avons pas besoin de middleware supplémentaire comme dataValidation car nous obtenons toutes les informations nécessaires à partir du paramètre URL.

Extraction de l'ID du Post

Nous extrayons l'ID du post à partir des paramètres de la requête en utilisant req.params.id:

const postId = req.params.id;

Cette ligne capture la valeur :id de l'URL, nous permettant de travailler avec dans le code suivant.

Supprimer le Post

Voici comment nous supprimons le post :

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.splice(postIndex, 1);

await fs.writeFile("./database/posts.json", JSON.stringify(data));
  • Nous commençons par lire les données existantes à partir du fichier JSON en utilisant la fonction asynchrone readData, comme expliqué précédemment.
  • Nous trouvons l'index du post à supprimer dans le tableau data en comparant les IDs des posts.
  • Si le post n'est pas trouvé (c'est-à-dire, postIndex === -1), nous retournons une réponse 404 (Non Trouvé) avec un message d'erreur.
  • En utilisant la méthode splice, nous supprimons les données du post du tableau data. La variable postIndex détermine la position du post à supprimer.
  • Le tableau data mis à jour, avec le post supprimé, est ensuite réécrit dans le fichier JSON pour enregistrer les modifications effectuées lors de la suppression.

Envoi d'une Réponse

Une réponse JSON avec un code de statut 200 (OK) est envoyée au client, indiquant une suppression réussie. La réponse inclut un message confirmant que le post a été supprimé avec succès :

res.status(200).json({ message: "Post deleted successfully" });

Gestion des Erreurs

Nous enveloppons le code de la route dans un bloc try-catch pour gérer les erreurs potentielles lors de la récupération des données ou du traitement de la requête. Toutes les erreurs qui se produisent sont enregistrées dans la console à des fins de débogage :

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

Code complet du fichier postsRoutes.js à cette étape

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

// DELETE POST BY ID
router.delete("/post/:id", async (req, res, next) => {
  try {
    // Extract the post ID from the request parameters
    const postId = req.params.id;

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

    // Remove the post from the data array using `splice`
    data.splice(postIndex, 1);

    // Write the updated data back to the data source (e.g., a JSON file)
    await fs.writeFile("./database/posts.json", JSON.stringify(data));

    // Send a success response with the JSON response indicating successful deletion
    res.status(200).json({ message: "Post deleted successfully" });
  } catch (error) {
    console.error(error.message);
    next(error);
  }
});

module.exports = router;

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 4. Chapitre 9
some-alt