Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Création du Point de Terminaison DELETE pour Supprimer un Post par Identifiant | Création d'API REST avec Node.js et Express.js
Développement Backend avec Node.js et Express.js

bookCréation du Point de Terminaison DELETE pour Supprimer un Post par Identifiant

Nous allons examiner la mise en œuvre de la route « SUPPRIMER UN POST PAR ID » dans le fichier postsRoutes.js. Cette route permet aux clients de supprimer un post spécifique en fournissant son identifiant unique.

Définition de la route

Le code ci-dessous définit la route « SUPPRIMER UN POST PAR ID » en utilisant router.delete() :

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

Cette route gère les requêtes HTTP DELETE avec un paramètre :id dans le chemin de la route. Le paramètre :id est utilisé pour identifier le post à supprimer. Aucun middleware supplémentaire tel que dataValidation n'est nécessaire, car toutes les informations requises sont obtenues à partir du paramètre d'URL.

Extraction de l'identifiant du post

L'identifiant du post est extrait à partir des paramètres de la requête en utilisant req.params.id :

const postId = req.params.id;

Cette ligne récupère la valeur de :id depuis l'URL, ce qui permet de l'utiliser dans le code suivant.

Supprimer l’article

Voici comment supprimer l’article :

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));
  • Lecture des données existantes à partir du fichier JSON à l’aide de la fonction asynchrone readData, comme expliqué précédemment.
  • Recherche de l’index de l’article à supprimer dans le tableau data en comparant les identifiants des articles.
  • Si l’article n’est pas trouvé (c’est-à-dire postIndex === -1), une réponse 404 (Non trouvé) est renvoyée avec un message d’erreur.
  • Utilisation de la méthode splice pour retirer l’article du tableau data. La variable postIndex détermine la position de l’article à supprimer.
  • Le tableau data mis à jour, sans l’article supprimé, est ensuite réécrit dans le fichier JSON afin d’enregistrer les modifications effectuées lors de la suppression.

Envoi d’une réponse

Une réponse JSON avec un code d’état 200 (OK) est envoyée au client, indiquant que la suppression a réussi. La réponse inclut un message confirmant que l’article a été supprimé avec succès :

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

Gestion des erreurs

Le code de la route est encapsulé dans un bloc try-catch afin de gérer les erreurs potentielles lors de la récupération des données ou du traitement de la requête. Toute erreur survenant est enregistrée 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

Suggested prompts:

Can you explain how the error handling works in the DELETE route?

What would happen if the post ID provided does not exist?

Can you summarize the main steps involved in deleting a post?

Awesome!

Completion rate improved to 2.56

bookCréation du Point de Terminaison DELETE pour Supprimer un Post par Identifiant

Glissez pour afficher le menu

Nous allons examiner la mise en œuvre de la route « SUPPRIMER UN POST PAR ID » dans le fichier postsRoutes.js. Cette route permet aux clients de supprimer un post spécifique en fournissant son identifiant unique.

Définition de la route

Le code ci-dessous définit la route « SUPPRIMER UN POST PAR ID » en utilisant router.delete() :

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

Cette route gère les requêtes HTTP DELETE avec un paramètre :id dans le chemin de la route. Le paramètre :id est utilisé pour identifier le post à supprimer. Aucun middleware supplémentaire tel que dataValidation n'est nécessaire, car toutes les informations requises sont obtenues à partir du paramètre d'URL.

Extraction de l'identifiant du post

L'identifiant du post est extrait à partir des paramètres de la requête en utilisant req.params.id :

const postId = req.params.id;

Cette ligne récupère la valeur de :id depuis l'URL, ce qui permet de l'utiliser dans le code suivant.

Supprimer l’article

Voici comment supprimer l’article :

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));
  • Lecture des données existantes à partir du fichier JSON à l’aide de la fonction asynchrone readData, comme expliqué précédemment.
  • Recherche de l’index de l’article à supprimer dans le tableau data en comparant les identifiants des articles.
  • Si l’article n’est pas trouvé (c’est-à-dire postIndex === -1), une réponse 404 (Non trouvé) est renvoyée avec un message d’erreur.
  • Utilisation de la méthode splice pour retirer l’article du tableau data. La variable postIndex détermine la position de l’article à supprimer.
  • Le tableau data mis à jour, sans l’article supprimé, est ensuite réécrit dans le fichier JSON afin d’enregistrer les modifications effectuées lors de la suppression.

Envoi d’une réponse

Une réponse JSON avec un code d’état 200 (OK) est envoyée au client, indiquant que la suppression a réussi. La réponse inclut un message confirmant que l’article a été supprimé avec succès :

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

Gestion des erreurs

Le code de la route est encapsulé dans un bloc try-catch afin de gérer les erreurs potentielles lors de la récupération des données ou du traitement de la requête. Toute erreur survenant est enregistrée 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