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

bookIDで投稿を取得するエンドポイントの構築

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

postsRoutes.js file ファイル内で「GET POST BY ID」ルートの実装方法について解説。このルートは、URL の一部として指定された一意の識別子(id)に基づいて特定の投稿を取得し、返却。

注意

「database」という用語は、database フォルダー内の posts.json ファイルを指す。

ルート定義

以下のコードは、router.get() を使用して「GET POST BY ID」ルートを定義。

router.get("/post/:id", async (req, res, next) => { ... }
  • このルートは HTTP GET リクエストを処理するように設定。
  • ルートパス /post/:id にはパラメータ :id が含まれ、URL から投稿 ID を取得。

投稿 ID の抽出

リクエストパラメータから req.params.id を使って投稿 ID を抽出。

const postId = req.params.id;

この行で URL から :id の値を取得し、以降の処理で利用可能に。

データベースでの投稿検索

次に、データベース内で一致する ID の投稿を検索。

const data = await readData();

const post = data.find((post) => post.id === postId);
  • 非同期関数 readData を使い、JSON ファイルからデータを取得。
  • 取得したデータ内で、find() メソッドを用いて一致する ID の投稿を検索。
  • post 変数には、見つかった投稿または一致しない場合は undefined が格納。

レスポンスの処理

投稿が見つかったかどうかに基づいてレスポンスを処理:

if (!post) {
  res.status(404).json({ error: "Post not found" });
} else {
  res.status(200).send(post);
}
  • 投稿が見つからなかった場合(postundefined の場合)、404レスポンスとエラーメッセージを送信し、リクエストされた投稿が見つからなかったことを示す;
  • 投稿が見つかった場合、ステータスコード200(OK)で投稿をレスポンスとして送信。

エラー処理

データ取得やリクエスト処理中に発生する可能性のあるエラーを処理するため、ルートコードを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);
  }
});

すべて明確でしたか?

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

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

セクション 4.  6

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 4.  6
some-alt