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

bookGET全投稿エンドポイントの構築

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

postsRoutes.js ファイルで「GET ALL POSTS」ルートの実装方法について解説。 このルートはデータソース(database/posts.json)からすべての投稿リストを取得し、クライアントへのレスポンスとして送信。

必要なモジュールと依存関係のインポート

ファイルの冒頭で、必要なモジュールと依存関係をインポート:

const express = require("express");
const fs = require("fs/promises");
const validatePostData = require("../middlewares/validateData");
  • express: ルート構築のための Express フレームワーク;
  • fs/promises: JSON ファイルからデータを読み込むための非同期ファイル操作モジュール;
  • validatePostData: このルートでは未使用だが、後の章でデータ検証に役立つ validatePostData ミドルウェア。

Expressルーターの初期化

このファイル内で定義されたすべてのルートを処理するExpressルーターのインスタンスを初期化。

const router = express.Router();

データを読み込む関数の作成

JSONファイルからデータを読み込む非同期関数readDataを定義。データが正しく取得されることを保証し、エラー処理も実装。

// 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;
  }
}
  • fs.readFile: fs.readFileファイルの内容を読み込むために./database/posts.jsonを使用。
  • JSON.parse: ファイルから取得したデータをJavaScriptオブジェクトに変換。
  • エラー処理: 読み込みやパース処理中にエラーが発生した場合は、エラーをキャッチしてスロー。

「GET ALL POSTS」ルートの定義

ルーター内で「GET ALL POSTS」ルートを定義する方法。

// 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
  }
});

ルート定義: このルートはルートパス(/)へのHTTP GETリクエストを処理。

ルートハンドラー: ルートハンドラー関数内では、

  • readData関数を呼び出してJSONファイルから投稿リストを取得;
  • データ取得が成功した場合、res.send(data)で取得したデータをレスポンスとして送信;
  • この処理中にエラーが発生した場合は、エラーをキャッチし、デバッグのためにコンソールにログ出力(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
  }
});

すべて明確でしたか?

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

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

セクション 4.  5

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 4.  5
some-alt