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

bookIDによるDelete投稿エンドポイントの構築

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

postsRoutes.js ファイル内で「DELETE POST BY ID」ルートの実装について説明。 このルートは、クライアントが特定の投稿のユニークなIDを指定して削除できるようにするもの。

ルート定義

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

router.delete("/post/:id", async (req, res, next) => { ... }

このルートは、ルートパス内のパラメータ化された :id を持つ HTTP DELETE リクエストを処理。 :id パラメータは削除対象の投稿を識別するために使用。 URL パラメータからすべての必要な情報を取得できるため、dataValidation のような追加ミドルウェアは不要。

投稿IDの抽出

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

const postId = req.params.id;

このコード行は、URL から :id の値を取得し、以降のコードで利用可能にする。

投稿の削除

投稿を削除する方法は以下の通りです:

const data = await readData();

const postIndex = data.findIndex((post) => post.id === postId);

if (postIndex === -1) {
  return res.status(404).json({ error: "Post not found" });
}

data.splice(postIndex, 1);

await fs.writeFile("./database/posts.json", JSON.stringify(data));
  • 既存のデータを非同期関数 readData を使ってJSONファイルから読み込みます(前述参照)。
  • 削除対象の投稿IDを比較し、data 配列内で該当する投稿のインデックスを検索します。
  • 投稿が見つからない場合(postIndex === -1)、404(Not Found)レスポンスとエラーメッセージを返します。
  • splice メソッドを使い、data 配列から該当する投稿データを削除します。postIndex 変数が削除対象の位置を示します。
  • 投稿を削除した後の更新済み data 配列をJSONファイルに書き戻し、削除操作の変更を保存します。

レスポンスの送信

削除が成功したことを示す200(OK)ステータスコードとともに、クライアントへJSONレスポンスが送信されます。レスポンスには、投稿が正常に削除されたことを確認するメッセージが含まれます:

res.status(200).json({ message: "Post deleted successfully" });

エラーハンドリング

データ取得やリクエスト処理中に発生する可能性のあるエラーを処理するため、ルートコード全体を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 {
    const newPost = {
      id: Date.now().toString(), // Generate a unique ID for the new post
      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);
  }
});

// UPDATE POST BY ID
router.put("/post/:id", validatePostData, async (req, res, next) => {
  try {
    // Extract the post ID from the request parameters
    const postId = req.params.id;
    // Extract the updated data from the request body
    const updatedData = {
      username: req.body.username,
      postTitle: req.body.postTitle,
      postContent: req.body.postContent,
    };

    // Read the existing data
    const data = await readData();

    // Find the index of the post with the specified ID in the data array
    const postIndex = data.findIndex((post) => post.id === postId);

    // If the post with the specified ID doesn't exist, return a 404 error
    if (postIndex === -1) {
      return res.status(404).json({ error: "Post not found" });
    }

    // Update the post data with the new data using spread syntax
    data[postIndex] = {
      ...data[postIndex], // Keep existing data
      ...updatedData, // Apply updated data
    };

    // Write the updated data back
    await fs.writeFile("./database/posts.json", JSON.stringify(data));

    // Send a success response with the updated post
    res.status(200).json(data[postIndex]);
  } catch (error) {
    console.error(error.message);
    next(error);
  }
});

// DELETE POST BY ID
router.delete("/post/:id", async (req, res, next) => {
  try {
    // Extract the post ID from the request parameters
    const postId = req.params.id;

    // Read the existing data
    const data = await readData();

    // Find the index of the post with the specified ID in the data array
    const postIndex = data.findIndex((post) => post.id === postId);

    // If the post with the specified ID doesn't exist, return a 404 error
    if (postIndex === -1) {
      return res.status(404).json({ error: "Post not found" });
    }

    // Remove the post from the data array using `splice`
    data.splice(postIndex, 1);

    // Write the updated data back to the data source (e.g., a JSON file)
    await fs.writeFile("./database/posts.json", JSON.stringify(data));

    // Send a success response with the JSON response indicating successful deletion
    res.status(200).json({ message: "Post deleted successfully" });
  } catch (error) {
    console.error(error.message);
    next(error);
  }
});

module.exports = router;

すべて明確でしたか?

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

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

セクション 4.  9

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 4.  9
some-alt