Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Creación del Endpoint DELETE para Eliminar una Publicación por Id | Creación de API REST con Node.js y Express.js
Desarrollo Backend con Node.js y Express.js

bookCreación del Endpoint DELETE para Eliminar una Publicación por Id

Exploraremos la implementación de la ruta "ELIMINAR PUBLICACIÓN POR ID" dentro del archivo postsRoutes.js. Esta ruta permite a los clientes eliminar una publicación específica proporcionando su ID único.

Definición de la Ruta

El siguiente código define la ruta "ELIMINAR PUBLICACIÓN POR ID" utilizando router.delete():

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

Esta ruta gestiona solicitudes HTTP DELETE con un parámetro :id en la ruta. El parámetro :id se utiliza para identificar la publicación que se va a eliminar. No se requiere middleware adicional como dataValidation, ya que toda la información necesaria se obtiene del parámetro de la URL.

Extracción del ID de la Publicación

Se extrae el ID de la publicación de los parámetros de la solicitud utilizando req.params.id:

const postId = req.params.id;

Esta línea captura el valor de :id desde la URL, permitiendo trabajar con él en el código posterior.

Eliminar la publicación

Así es como eliminamos la publicación:

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));
  • Comenzamos leyendo los datos existentes del archivo JSON utilizando la función asíncrona readData, como se explicó anteriormente.
  • Buscamos el índice de la publicación a eliminar en el arreglo data comparando los IDs de las publicaciones.
  • Si la publicación no se encuentra (es decir, postIndex === -1), devolvemos una respuesta 404 (No Encontrado) con un mensaje de error.
  • Usando el método splice, eliminamos los datos de la publicación del arreglo data. La variable postIndex determina la posición de la publicación a eliminar.
  • El arreglo data actualizado, con la publicación eliminada, se escribe nuevamente en el archivo JSON para guardar los cambios realizados durante la eliminación.

Envío de una respuesta

Se envía una respuesta JSON con un código de estado 200 (OK) al cliente, indicando que la eliminación fue exitosa. La respuesta incluye un mensaje que confirma que la publicación fue eliminada correctamente:

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

Manejo de errores

Encapsulamos el código de la ruta en un bloque try-catch para manejar posibles errores durante la recuperación de datos o el procesamiento de la solicitud. Cualquier error que ocurra se registra en la consola para fines de depuración:

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

Código completo del archivo postsRoutes.js en este paso

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;

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 9

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Awesome!

Completion rate improved to 2.56

bookCreación del Endpoint DELETE para Eliminar una Publicación por Id

Desliza para mostrar el menú

Exploraremos la implementación de la ruta "ELIMINAR PUBLICACIÓN POR ID" dentro del archivo postsRoutes.js. Esta ruta permite a los clientes eliminar una publicación específica proporcionando su ID único.

Definición de la Ruta

El siguiente código define la ruta "ELIMINAR PUBLICACIÓN POR ID" utilizando router.delete():

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

Esta ruta gestiona solicitudes HTTP DELETE con un parámetro :id en la ruta. El parámetro :id se utiliza para identificar la publicación que se va a eliminar. No se requiere middleware adicional como dataValidation, ya que toda la información necesaria se obtiene del parámetro de la URL.

Extracción del ID de la Publicación

Se extrae el ID de la publicación de los parámetros de la solicitud utilizando req.params.id:

const postId = req.params.id;

Esta línea captura el valor de :id desde la URL, permitiendo trabajar con él en el código posterior.

Eliminar la publicación

Así es como eliminamos la publicación:

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));
  • Comenzamos leyendo los datos existentes del archivo JSON utilizando la función asíncrona readData, como se explicó anteriormente.
  • Buscamos el índice de la publicación a eliminar en el arreglo data comparando los IDs de las publicaciones.
  • Si la publicación no se encuentra (es decir, postIndex === -1), devolvemos una respuesta 404 (No Encontrado) con un mensaje de error.
  • Usando el método splice, eliminamos los datos de la publicación del arreglo data. La variable postIndex determina la posición de la publicación a eliminar.
  • El arreglo data actualizado, con la publicación eliminada, se escribe nuevamente en el archivo JSON para guardar los cambios realizados durante la eliminación.

Envío de una respuesta

Se envía una respuesta JSON con un código de estado 200 (OK) al cliente, indicando que la eliminación fue exitosa. La respuesta incluye un mensaje que confirma que la publicación fue eliminada correctamente:

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

Manejo de errores

Encapsulamos el código de la ruta en un bloque try-catch para manejar posibles errores durante la recuperación de datos o el procesamiento de la solicitud. Cualquier error que ocurra se registra en la consola para fines de depuración:

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

Código completo del archivo postsRoutes.js en este paso

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;

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 9
some-alt