IDによる投稿のUpdateエンドポイントの構築
メニューを表示するにはスワイプしてください
postsRoutes.js ファイル内の「UPDATE POST BY ID」ルートを使用して、既存の投稿を更新する方法について解説。
このルートは、投稿の一意なIDに基づいて投稿を更新する処理を担当。
ルート定義
以下のコードは、router.put() を使用して「UPDATE POST BY ID」ルートを定義。
router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
- このルートは、投稿の更新専用に HTTP PUT リクエストを処理するよう設定;
- ルートパスにパラメータ化された
:idを含み、更新対象の投稿を識別; validatePostDataミドルウェアを追加し、処理前にデータ検証を実施。validatePostDataミドルウェアのロジックは前のステップと同様。
リクエストからのデータ取得
ここでは、リクエストから必要なデータ(投稿IDおよび更新後の投稿内容)を抽出します。
const postId = req.params.id;
const updatedData = {
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
- 投稿IDはリクエストパラメータから抽出され、後続の処理で利用可能となります。ルートURLの
:idパラメータはreq.params.idで取得します。 username、postTitle、postContentはリクエストボディから抽出されます。
データベース内の投稿の更新
既存の投稿を更新するには、以下の手順を実行します。
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[postIndex] = {
...data[postIndex],
...updatedData,
};
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- 非同期関数
readDataを使用して、既存のデータをJSONファイルから読み込みます(前述の説明参照)。 postIndex変数には、投稿IDを比較して更新対象の投稿がdata配列内で持つインデックスが格納されます。- 投稿が見つからない場合(
postIndex === -1)、404(Not Found)エラーとともにエラーメッセージをクライアントに返します。 - 投稿データを更新する際は、既存の投稿データ(
...data[postIndex])と更新データ(...updatedData)をマージします。これにより、指定されたフィールドのみが更新され、既存データは保持されます。 - 最後に、更新後の
data配列をJSONファイルに書き戻し、変更内容を保存します。
レスポンスの送信
投稿の更新が成功した場合、クライアントにJSONレスポンスが送信されます。レスポンスには、200(OK)のステータスコードと、更新後の投稿データが含まれます。
res.status(200).json(data[postIndex]);
エラーハンドリング
ルートコードを 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);
}
});
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 8
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 8