Створення Кінцевої Точки Оновлення Поста За Ідентифікатором
Свайпніть щоб показати меню
Ми розглянемо, як оновити існуючий пост за допомогою маршруту "UPDATE POST BY ID" у файлі postsRoutes.js. Цей маршрут відповідає за оновлення поста на основі його унікального ідентифікатора.
Визначення маршруту
Наведений нижче код визначає маршрут "UPDATE POST BY ID" з використанням router.put():
router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
- Цей маршрут налаштований для обробки HTTP PUT-запитів, зокрема для оновлення постів;
- У шляху маршруту використовується параметр
:idдля ідентифікації поста, який потрібно оновити; - Додається проміжне програмне забезпечення
validatePostDataдля забезпечення валідації даних перед виконанням основної логіки. Логіка middlewarevalidatePostDataзалишається такою ж, як і на попередньому кроці.
Отримання даних із запиту
Тут ми витягуємо необхідні дані із запиту, включаючи ідентифікатор поста та оновлений вміст поста:
const postId = req.params.id;
const updatedData = {
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
- Ідентифікатор поста отримується з параметрів запиту, що дозволяє використовувати його для подальшої обробки. Параметр
:idз URL маршруту захоплюється за допомогоюreq.params.id; username,postTitleтаpostContentотримуються з тіла запиту.
Оновлення поста в базі даних
Оновлення існуючого поста включає декілька кроків, описаних нижче:
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));
- Ми зчитуємо наявні дані з JSON-файлу за допомогою асинхронної функції
readData, як було пояснено раніше; - Змінна
postIndexзберігає індекс поста, який потрібно оновити, у масивіdataшляхом порівняння ідентифікаторів постів; - Якщо пост не знайдено (тобто
postIndex === -1), клієнту повертається відповідь 404 (Не знайдено) з повідомленням про помилку; - Для оновлення даних поста ми об'єднуємо наявні дані поста (
...data[postIndex]) з оновленими даними (...updatedData). Це гарантує, що будуть оновлені лише вказані поля, а існуючі дані збережуться; - Нарешті, оновлений масив
dataзаписується назад у JSON-файл для збереження змін у пості.
Надсилання відповіді
Після успішного оновлення поста клієнту надсилається JSON-відповідь. Відповідь містить код статусу 200 (OK), що вказує на успішне оновлення, а також оновлені дані поста.
res.status(200).json(data[postIndex]);
Обробка помилок
Ми обгортаємо код маршруту у блок try-catch для обробки можливих помилок під час отримання даних або обробки запиту. Усі помилки, що виникають, записуються у консоль для налагодження:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Повний код файлу postsRoutes.js на цьому етапі
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);
}
});
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат