 Створення Кінцевої Точки CREATE Для Поста
Створення Кінцевої Точки CREATE Для Поста
Ми розглянемо створення нового поста за допомогою маршруту "CREATE POST" у файлі postsRoutes.js. Цей маршрут відповідає за обробку створення поста та збереження його у джерелі даних (database/posts.json).
Визначення маршруту
Наведений нижче код визначає маршрут "CREATE POST" за допомогою router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Цей маршрут налаштовано для обробки HTTP POST-запитів до кореневого шляху /;
- Використовується проміжне програмне забезпечення validatePostData, яке перевіряє коректність даних у тілі запиту перед подальшою обробкою.
Проміжне програмне забезпечення для валідації даних
Перед тим як перейти до логіки маршруту, необхідно створити проміжне програмне забезпечення для валідації даних. Це проміжне ПЗ гарантує, що дані, надіслані у тілі запиту, є коректними перед спробою створити новий пост.
// Middleware to validate post data
function validatePostData(req, res, next) {
  const { username, postTitle, postContent } = req.body;
  if (!username || !postTitle || !postContent) {
    return res.status(400).json({ error: "Missing required fields" });
  }
  // If data is valid, proceed to the next route handler
  next();
}
- Функція validatePostDataотримуєusername,postTitleтаpostContentз тіла запиту;
- Вона перевіряє наявність цих полів. Якщо будь-яке з них відсутнє (!username,!postTitleабо!postContent), повертається статус-код 400 (Bad Request) та повідомлення про відсутність обов'язкових полів;
- Якщо дані коректні, проміжне ПЗ викликає next(), дозволяючи запиту перейти до обробника маршруту (у цьому випадку — до маршруту "CREATE POST").
Після додавання проміжного ПЗ для валідації даних, продовжимо з логікою маршруту "CREATE POST".
Дані нового поста
Для створення нового поста генерується унікальний ідентифікатор за допомогою Date.now().toString(). Додатково отримуються username, postTitle та postContent з тіла запиту.
const newPost = {
  id: Date.now().toString(),
  username: req.body.username,
  postTitle: req.body.postTitle,
  postContent: req.body.postContent,
};
Додавання нового поста до бази даних
Наведені нижче кроки описують, як новий пост додається до бази даних:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Існуючі дані зчитуються з JSON-файлу за допомогою асинхронної функції readData, як було описано раніше;
- Новий пост додається до масиву data;
- Оновлений масив dataзаписується назад у JSON-файл для збереження нового поста.
Відправлення відповіді
Після успішного створення нового поста клієнту надсилається відповідь про успіх. Відповідь містить статус-код 201 (Created) та деталі щойно створеного поста у форматі JSON.
res.status(201).json(newPost);
Обробка помилок
Код маршруту обгортається у блок try-catch для обробки можливих помилок під час отримання даних або обробки запиту. Усі помилки, що виникають, логуються у консоль для налагодження:
try {
  // ... (code for retrieving and processing data)
} catch (error) {
  console.error(error.message);
}
Complete code of the postsRoutes.js file at this step
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 {
    // Generate a unique ID for the new post
    const newPost = {
      id: Date.now().toString(),
      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);
  }
});
Повний код файлу validateData.js
// Middleware to validate post data
function validatePostData(req, res, next) {
  const { username, postTitle, postContent } = req.body;
  if (!username || !postTitle || !postContent) {
    return res.status(400).json({ error: "Missing required fields" });
  }
  // If data is valid, proceed to the next route handler
  next();
}
module.exports = validatePostData;
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you explain how the validatePostData middleware works in more detail?
What happens if there is an error while writing to the posts.json file?
How can I test the "CREATE POST" route using a tool like Postman?
Awesome!
Completion rate improved to 2.56 Створення Кінцевої Точки CREATE Для Поста
Створення Кінцевої Точки CREATE Для Поста
Свайпніть щоб показати меню
Ми розглянемо створення нового поста за допомогою маршруту "CREATE POST" у файлі postsRoutes.js. Цей маршрут відповідає за обробку створення поста та збереження його у джерелі даних (database/posts.json).
Визначення маршруту
Наведений нижче код визначає маршрут "CREATE POST" за допомогою router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Цей маршрут налаштовано для обробки HTTP POST-запитів до кореневого шляху /;
- Використовується проміжне програмне забезпечення validatePostData, яке перевіряє коректність даних у тілі запиту перед подальшою обробкою.
Проміжне програмне забезпечення для валідації даних
Перед тим як перейти до логіки маршруту, необхідно створити проміжне програмне забезпечення для валідації даних. Це проміжне ПЗ гарантує, що дані, надіслані у тілі запиту, є коректними перед спробою створити новий пост.
// Middleware to validate post data
function validatePostData(req, res, next) {
  const { username, postTitle, postContent } = req.body;
  if (!username || !postTitle || !postContent) {
    return res.status(400).json({ error: "Missing required fields" });
  }
  // If data is valid, proceed to the next route handler
  next();
}
- Функція validatePostDataотримуєusername,postTitleтаpostContentз тіла запиту;
- Вона перевіряє наявність цих полів. Якщо будь-яке з них відсутнє (!username,!postTitleабо!postContent), повертається статус-код 400 (Bad Request) та повідомлення про відсутність обов'язкових полів;
- Якщо дані коректні, проміжне ПЗ викликає next(), дозволяючи запиту перейти до обробника маршруту (у цьому випадку — до маршруту "CREATE POST").
Після додавання проміжного ПЗ для валідації даних, продовжимо з логікою маршруту "CREATE POST".
Дані нового поста
Для створення нового поста генерується унікальний ідентифікатор за допомогою Date.now().toString(). Додатково отримуються username, postTitle та postContent з тіла запиту.
const newPost = {
  id: Date.now().toString(),
  username: req.body.username,
  postTitle: req.body.postTitle,
  postContent: req.body.postContent,
};
Додавання нового поста до бази даних
Наведені нижче кроки описують, як новий пост додається до бази даних:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Існуючі дані зчитуються з JSON-файлу за допомогою асинхронної функції readData, як було описано раніше;
- Новий пост додається до масиву data;
- Оновлений масив dataзаписується назад у JSON-файл для збереження нового поста.
Відправлення відповіді
Після успішного створення нового поста клієнту надсилається відповідь про успіх. Відповідь містить статус-код 201 (Created) та деталі щойно створеного поста у форматі JSON.
res.status(201).json(newPost);
Обробка помилок
Код маршруту обгортається у блок try-catch для обробки можливих помилок під час отримання даних або обробки запиту. Усі помилки, що виникають, логуються у консоль для налагодження:
try {
  // ... (code for retrieving and processing data)
} catch (error) {
  console.error(error.message);
}
Complete code of the postsRoutes.js file at this step
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 {
    // Generate a unique ID for the new post
    const newPost = {
      id: Date.now().toString(),
      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);
  }
});
Повний код файлу validateData.js
// Middleware to validate post data
function validatePostData(req, res, next) {
  const { username, postTitle, postContent } = req.body;
  if (!username || !postTitle || !postContent) {
    return res.status(400).json({ error: "Missing required fields" });
  }
  // If data is valid, proceed to the next route handler
  next();
}
module.exports = validatePostData;
Дякуємо за ваш відгук!