Bygga Update-endpunkt för Post med Id
Vi kommer att undersöka hur man uppdaterar ett befintligt inlägg med hjälp av "UPDATE POST BY ID"-rutten i filen postsRoutes.js. Denna rutt hanterar uppdateringen av ett inlägg baserat på dess unika ID.
Ruttdefinition
Koden nedan definierar "UPDATE POST BY ID"-rutten med hjälp av router.put():
router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
- Denna rutt är konfigurerad för att hantera HTTP PUT-förfrågningar, specifikt för att uppdatera inlägg;
- Den inkluderar en parameteriserad
:idi ruttvägen för att identifiera vilket inlägg som ska uppdateras; - Middleware-funktionen
validatePostDataläggs till för att säkerställa datavalidering innan processen fortsätter. Logiken förvalidatePostData-middleware är oförändrad från föregående steg.
Hämta data från förfrågan
Här extraheras nödvändig data från förfrågan, inklusive inläggets ID och det uppdaterade inläggsinnehållet:
const postId = req.params.id;
const updatedData = {
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
- Inläggets ID hämtas från förfrågans parametrar och görs tillgängligt för vidare bearbetning. Parametern
:idfrån routens URL fångas medreq.params.id; username,postTitleochpostContenthämtas från förfrågans body.
Uppdatera inlägget i databasen
Att uppdatera ett befintligt inlägg innebär flera steg, enligt nedan:
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[postIndex] = {
...data[postIndex],
...updatedData,
};
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Vi läser in befintlig data från JSON-filen med den asynkrona funktionen
readData, som förklarats tidigare; - Variabeln
postIndexlagrar indexet för det inlägg som ska uppdateras i arrayendatagenom att jämföra inläggs-ID:n; - Om inlägget inte hittas (dvs.
postIndex === -1), returneras ett 404 (Not Found)-svar med ett felmeddelande till klienten; - För att uppdatera inläggets data slås befintlig inläggsdata (
...data[postIndex]) samman med den uppdaterade datan (...updatedData). Detta säkerställer att endast angivna fält uppdateras och befintlig data behålls; - Slutligen skrivs den uppdaterade arrayen
datatillbaka till JSON-filen för att spara ändringarna av inlägget.
Skicka ett svar
När inlägget har uppdaterats skickas ett JSON-svar till klienten. Svaret innehåller statuskod 200 (OK), vilket indikerar en lyckad uppdatering samt den uppdaterade inläggsdatan.
res.status(200).json(data[postIndex]);
Felhantering
Vi omsluter rutkoden i ett try-catch-block för att hantera potentiella fel under datahämtning eller begäransbearbetning. Alla 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);
}
});
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 2.56
Bygga Update-endpunkt för Post med Id
Svep för att visa menyn
Vi kommer att undersöka hur man uppdaterar ett befintligt inlägg med hjälp av "UPDATE POST BY ID"-rutten i filen postsRoutes.js. Denna rutt hanterar uppdateringen av ett inlägg baserat på dess unika ID.
Ruttdefinition
Koden nedan definierar "UPDATE POST BY ID"-rutten med hjälp av router.put():
router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
- Denna rutt är konfigurerad för att hantera HTTP PUT-förfrågningar, specifikt för att uppdatera inlägg;
- Den inkluderar en parameteriserad
:idi ruttvägen för att identifiera vilket inlägg som ska uppdateras; - Middleware-funktionen
validatePostDataläggs till för att säkerställa datavalidering innan processen fortsätter. Logiken förvalidatePostData-middleware är oförändrad från föregående steg.
Hämta data från förfrågan
Här extraheras nödvändig data från förfrågan, inklusive inläggets ID och det uppdaterade inläggsinnehållet:
const postId = req.params.id;
const updatedData = {
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
- Inläggets ID hämtas från förfrågans parametrar och görs tillgängligt för vidare bearbetning. Parametern
:idfrån routens URL fångas medreq.params.id; username,postTitleochpostContenthämtas från förfrågans body.
Uppdatera inlägget i databasen
Att uppdatera ett befintligt inlägg innebär flera steg, enligt nedan:
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[postIndex] = {
...data[postIndex],
...updatedData,
};
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Vi läser in befintlig data från JSON-filen med den asynkrona funktionen
readData, som förklarats tidigare; - Variabeln
postIndexlagrar indexet för det inlägg som ska uppdateras i arrayendatagenom att jämföra inläggs-ID:n; - Om inlägget inte hittas (dvs.
postIndex === -1), returneras ett 404 (Not Found)-svar med ett felmeddelande till klienten; - För att uppdatera inläggets data slås befintlig inläggsdata (
...data[postIndex]) samman med den uppdaterade datan (...updatedData). Detta säkerställer att endast angivna fält uppdateras och befintlig data behålls; - Slutligen skrivs den uppdaterade arrayen
datatillbaka till JSON-filen för att spara ändringarna av inlägget.
Skicka ett svar
När inlägget har uppdaterats skickas ett JSON-svar till klienten. Svaret innehåller statuskod 200 (OK), vilket indikerar en lyckad uppdatering samt den uppdaterade inläggsdatan.
res.status(200).json(data[postIndex]);
Felhantering
Vi omsluter rutkoden i ett try-catch-block för att hantera potentiella fel under datahämtning eller begäransbearbetning. Alla 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);
}
});
Tack för dina kommentarer!