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

IDによるGETポストエンドポイントの構築

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

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

Note
注記

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

ルート定義

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

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

投稿IDの抽出

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

const postId = req.params.id;

この行はURLから :id の値を取得し、後続の処理で利用可能にする。

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

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

const data = await readData();

const post = data.find((post) => post.id === postId);
  • 非同期関数 readData を使用してJSONファイルからデータを取得;
  • 取得したデータ内で一致するIDを持つ投稿を見つけるために find() メソッドを使用;
  • 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