Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ CREATEポストエンドポイントの構築 | Node.jsとExpress.jsによるREST API構築
Node.jsとExpress.jsによるバックエンド開発

bookCREATEポストエンドポイントの構築

メニューを表示するにはスワイプしてください

postsRoutes.js ファイル内の「CREATE POST」ルートを使用して新しい投稿を作成する方法について説明。 このルートは投稿の作成と、データソース(database/posts.json)への保存を担当。

ルート定義

以下のコードは、router.post() を使用して「CREATE 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関数は、リクエストボディからusernamepostTitlepostContentを抽出します。
  • これらのフィールドが存在するかどうかを確認します。いずれかが欠落している場合(!username!postTitle、または!postContent)、400(Bad Request)ステータスコードと必須フィールドが不足していることを示すエラーメッセージで応答します。
  • データが有効な場合、ミドルウェアはnext()を呼び出し、リクエストをルートハンドラー(この場合は「CREATE POST」ルート)に進めます。

データバリデーションミドルウェアが用意できたら、「CREATE POST」ルートのロジックに進みます。

新規投稿データ

新しい投稿を作成するために、Date.now().toString()を使用して一意のIDを生成します。さらに、リクエストボディからusernamepostTitlepostContentを抽出します。

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));
  • 既存のデータは、前述の非同期readData関数を使用してJSONファイルから読み込まれます。
  • 新しい投稿が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);
}

このステップでの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 {
    // 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;

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  7

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  7
some-alt