Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Skapa Delete-Endpunkt För Inlägg Via Id | Bygga REST API:er med Node.js och Express.js
Backendutveckling med Node.js och Express.js

bookSkapa Delete-Endpunkt För Inlägg Via Id

Vi kommer att fördjupa oss i implementeringen av "DELETE POST BY ID"-rutten i filen postsRoutes.js. Denna rutt möjliggör för klienter att ta bort ett specifikt inlägg genom att ange dess unika ID.

Ruttdefinition

Koden nedan definierar "DELETE POST BY ID"-rutten med hjälp av router.delete():

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

Denna rutt hanterar HTTP DELETE-förfrågningar med en parameteriserad :id i rutten. Parametern :id används för att identifiera det inlägg som ska tas bort. Vi behöver inte extra mellanprogram som dataValidation eftersom all nödvändig information hämtas från URL-parametern.

Extrahera inläggs-ID

Vi extraherar inläggs-ID från förfrågningsparametrarna med hjälp av req.params.id:

const postId = req.params.id;

Denna rad hämtar värdet för :id från URL:en, vilket gör det möjligt att arbeta med det i den efterföljande koden.

Ta bort inlägget

Så här tar vi bort inlägget:

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));
  • Vi börjar med att läsa in befintlig data från JSON-filen med den asynkrona funktionen readData, som förklarats tidigare.
  • Vi hittar indexet för det inlägg som ska tas bort i data-arrayen genom att jämföra post-ID:n.
  • Om inlägget inte hittas (dvs. postIndex === -1), returneras ett 404 (Not Found)-svar med ett felmeddelande.
  • Med hjälp av metoden splice tas inläggets data bort från data-arrayen. Variabeln postIndex anger positionen för det inlägg som ska tas bort.
  • Den uppdaterade data-arrayen, där inlägget tagits bort, skrivs sedan tillbaka till JSON-filen för att spara ändringarna som gjorts vid borttagningen.

Skicka ett svar

Ett JSON-svar med statuskod 200 (OK) skickas till klienten, vilket indikerar att borttagningen lyckades. Svaret innehåller ett meddelande som bekräftar att inlägget har tagits bort:

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

Felhantering

Vi kapslar in ruttkoden i ett try-catch-block för att hantera potentiella fel vid datahämtning eller begäranhantering. Eventuella fel som uppstår loggas till konsolen för felsökningsändamål:

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

Komplett kod för postsRoutes.js-filen vid detta steg

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;

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 9

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

bookSkapa Delete-Endpunkt För Inlägg Via Id

Svep för att visa menyn

Vi kommer att fördjupa oss i implementeringen av "DELETE POST BY ID"-rutten i filen postsRoutes.js. Denna rutt möjliggör för klienter att ta bort ett specifikt inlägg genom att ange dess unika ID.

Ruttdefinition

Koden nedan definierar "DELETE POST BY ID"-rutten med hjälp av router.delete():

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

Denna rutt hanterar HTTP DELETE-förfrågningar med en parameteriserad :id i rutten. Parametern :id används för att identifiera det inlägg som ska tas bort. Vi behöver inte extra mellanprogram som dataValidation eftersom all nödvändig information hämtas från URL-parametern.

Extrahera inläggs-ID

Vi extraherar inläggs-ID från förfrågningsparametrarna med hjälp av req.params.id:

const postId = req.params.id;

Denna rad hämtar värdet för :id från URL:en, vilket gör det möjligt att arbeta med det i den efterföljande koden.

Ta bort inlägget

Så här tar vi bort inlägget:

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));
  • Vi börjar med att läsa in befintlig data från JSON-filen med den asynkrona funktionen readData, som förklarats tidigare.
  • Vi hittar indexet för det inlägg som ska tas bort i data-arrayen genom att jämföra post-ID:n.
  • Om inlägget inte hittas (dvs. postIndex === -1), returneras ett 404 (Not Found)-svar med ett felmeddelande.
  • Med hjälp av metoden splice tas inläggets data bort från data-arrayen. Variabeln postIndex anger positionen för det inlägg som ska tas bort.
  • Den uppdaterade data-arrayen, där inlägget tagits bort, skrivs sedan tillbaka till JSON-filen för att spara ändringarna som gjorts vid borttagningen.

Skicka ett svar

Ett JSON-svar med statuskod 200 (OK) skickas till klienten, vilket indikerar att borttagningen lyckades. Svaret innehåller ett meddelande som bekräftar att inlägget har tagits bort:

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

Felhantering

Vi kapslar in ruttkoden i ett try-catch-block för att hantera potentiella fel vid datahämtning eller begäranhantering. Eventuella fel som uppstår loggas till konsolen för felsökningsändamål:

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

Komplett kod för postsRoutes.js-filen vid detta steg

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;

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 9
some-alt