Opbygning af Delete-endpoint for Post Efter Id
Stryg for at vise menuen
Vi gennemgår implementeringen af "DELETE POST BY ID"-ruten i filen postsRoutes.js. Denne rute gør det muligt for klienter at slette et specifikt opslag ved at angive dets unikke ID.
Rutedefinition
Koden nedenfor definerer "DELETE POST BY ID"-ruten ved hjælp af router.delete():
router.delete("/post/:id", async (req, res, next) => { ... }
Denne rute håndterer HTTP DELETE-anmodninger med en parameteriseret :id i rutestien. :id-parameteren bruges til at identificere det opslag, der skal slettes. Vi behøver ikke ekstra middleware som dataValidation, da vi får alle nødvendige oplysninger fra URL-parameteren.
Udtrækning af opslagets ID
Vi udtrækker opslagets ID fra anmodningsparametrene ved hjælp af req.params.id:
const postId = req.params.id;
Denne linje opfanger værdien af :id fra URL'en, hvilket gør det muligt at arbejde med den i den efterfølgende kode.
Slet posten
Sådan slettes posten:
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));
- Processen starter med at læse de eksisterende data fra JSON-filen ved hjælp af den asynkrone
readData-funktion, som tidligere beskrevet. - Indekset for den post, der skal slettes, findes i
data-arrayet ved at sammenligne post-ID'er. - Hvis posten ikke findes (dvs.
postIndex === -1), returneres et 404 (Not Found)-svar med en fejlmeddelelse. - Ved hjælp af
splice-metoden fjernes postens data fradata-arrayet. VariablenpostIndexangiver positionen for den post, der skal slettes. - Det opdaterede
data-array, hvor posten er fjernet, skrives derefter tilbage til JSON-filen for at gemme ændringerne, der blev foretaget under sletningen.
Afsendelse af svar
Et JSON-svar med statuskoden 200 (OK) sendes til klienten, hvilket indikerer en vellykket sletning. Svaret indeholder en besked, der bekræfter, at posten blev slettet:
res.status(200).json({ message: "Post deleted successfully" });
Fejlhåndtering
Rutekoden indkapsles i et try-catch-blok for at håndtere potentielle fejl under datahentning eller anmodningsbehandling. Eventuelle fejl, der opstår, logges til konsollen til fejlsøgningsformål:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Komplet kode for postsRoutes.js-filen på dette trin
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;
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat