Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Bygge Delete-endepunkt for Innlegg Etter Id | Bygge REST-API-er med Node.js og Express.js
Backend-Utvikling med Node.js og Express.js

bookBygge Delete-endepunkt for Innlegg Etter Id

Vi skal se nærmere på implementeringen av "DELETE POST BY ID"-ruten i postsRoutes.js-filen. Denne ruten gjør det mulig for klienter å slette et spesifikt innlegg ved å oppgi dets unike ID.

Rutedefinisjon

Koden under definerer "DELETE POST BY ID"-ruten ved bruk av router.delete():

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

Denne ruten håndterer HTTP DELETE-forespørsler med en parameterisert :id i ruteveien. :id-parameteren brukes til å identifisere innlegget som skal slettes. Vi trenger ikke ekstra mellomvare som dataValidation siden all nødvendig informasjon hentes fra URL-parameteren.

Hente ut innleggs-ID

Vi henter ut innleggs-ID-en fra forespørselsparameterne ved å bruke req.params.id:

const postId = req.params.id;

Denne linjen fanger opp verdien til :id fra URL-en, slik at vi kan bruke den videre i koden.

Slette innlegget

Slik sletter vi innlegget:

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));
  • Starter med å lese eksisterende data fra JSON-filen ved hjelp av den asynkrone readData-funksjonen, som tidligere forklart.
  • Finner indeksen til innlegget som skal slettes i data-arrayet ved å sammenligne post-ID-er.
  • Hvis innlegget ikke finnes (dvs. postIndex === -1), returneres en 404 (Ikke funnet)-respons med en feilmelding.
  • Ved å bruke splice-metoden fjernes innleggsdata fra data-arrayet. Variabelen postIndex bestemmer posisjonen til innlegget som skal slettes.
  • Den oppdaterte data-arrayen, med innlegget fjernet, skrives deretter tilbake til JSON-filen for å lagre endringene som ble gjort under slettingen.

Sende et svar

Et JSON-svar med statuskode 200 (OK) sendes til klienten, noe som indikerer at slettingen var vellykket. Svaret inkluderer en melding som bekrefter at innlegget ble slettet:

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

Feilhåndtering

Rutekoden pakkes inn i en try-catch-blokk for å håndtere potensielle feil under datainnhenting eller forespørselsbehandling. Eventuelle feil som oppstår logges til konsollen for feilsøkingsformål:

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

Komplett kode for postsRoutes.js-filen på dette steget

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;

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 9

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

bookBygge Delete-endepunkt for Innlegg Etter Id

Sveip for å vise menyen

Vi skal se nærmere på implementeringen av "DELETE POST BY ID"-ruten i postsRoutes.js-filen. Denne ruten gjør det mulig for klienter å slette et spesifikt innlegg ved å oppgi dets unike ID.

Rutedefinisjon

Koden under definerer "DELETE POST BY ID"-ruten ved bruk av router.delete():

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

Denne ruten håndterer HTTP DELETE-forespørsler med en parameterisert :id i ruteveien. :id-parameteren brukes til å identifisere innlegget som skal slettes. Vi trenger ikke ekstra mellomvare som dataValidation siden all nødvendig informasjon hentes fra URL-parameteren.

Hente ut innleggs-ID

Vi henter ut innleggs-ID-en fra forespørselsparameterne ved å bruke req.params.id:

const postId = req.params.id;

Denne linjen fanger opp verdien til :id fra URL-en, slik at vi kan bruke den videre i koden.

Slette innlegget

Slik sletter vi innlegget:

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));
  • Starter med å lese eksisterende data fra JSON-filen ved hjelp av den asynkrone readData-funksjonen, som tidligere forklart.
  • Finner indeksen til innlegget som skal slettes i data-arrayet ved å sammenligne post-ID-er.
  • Hvis innlegget ikke finnes (dvs. postIndex === -1), returneres en 404 (Ikke funnet)-respons med en feilmelding.
  • Ved å bruke splice-metoden fjernes innleggsdata fra data-arrayet. Variabelen postIndex bestemmer posisjonen til innlegget som skal slettes.
  • Den oppdaterte data-arrayen, med innlegget fjernet, skrives deretter tilbake til JSON-filen for å lagre endringene som ble gjort under slettingen.

Sende et svar

Et JSON-svar med statuskode 200 (OK) sendes til klienten, noe som indikerer at slettingen var vellykket. Svaret inkluderer en melding som bekrefter at innlegget ble slettet:

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

Feilhåndtering

Rutekoden pakkes inn i en try-catch-blokk for å håndtere potensielle feil under datainnhenting eller forespørselsbehandling. Eventuelle feil som oppstår logges til konsollen for feilsøkingsformål:

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

Komplett kode for postsRoutes.js-filen på dette steget

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;

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 9
some-alt