Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Het Bouwen van de Update-Post-op-Id-Endpoint | REST-API's Bouwen met Node.js en Express.js
Backendontwikkeling met Node.js en Express.js

bookHet Bouwen van de Update-Post-op-Id-Endpoint

We onderzoeken hoe een bestaande post kan worden bijgewerkt met behulp van de "UPDATE POST BY ID"-route in het bestand postsRoutes.js. Deze route verwerkt het bijwerken van een post op basis van zijn unieke ID.

Routedefinitie

De onderstaande code definieert de "UPDATE POST BY ID"-route met behulp van router.put():

router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
  • Deze route is geconfigureerd om HTTP PUT-verzoeken af te handelen, specifiek voor het bijwerken van posts;
  • Er is een geparameteriseerde :id in het routepad opgenomen om de bij te werken post te identificeren;
  • De middleware validatePostData is toegevoegd om gegevensvalidatie te waarborgen voordat wordt doorgegaan. De logica van de middleware validatePostData blijft hetzelfde als in de vorige stap.

Gegevens verkrijgen uit het verzoek

Hier worden de benodigde gegevens uit het verzoek gehaald, waaronder de post-ID en de bijgewerkte inhoud van de post:

const postId = req.params.id;
const updatedData = {
  username: req.body.username,
  postTitle: req.body.postTitle,
  postContent: req.body.postContent,
};
  • De post-ID wordt uit de request parameters gehaald, zodat deze beschikbaar is voor verdere verwerking. De :id parameter uit de route-URL wordt opgehaald met req.params.id;
  • De username, postTitle en postContent worden uit de body van het verzoek gehaald.

Post bijwerken in de database

Het bijwerken van een bestaande post omvat verschillende stappen, zoals hieronder beschreven:

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));
  • De bestaande gegevens worden uit het JSON-bestand gelezen met de asynchrone functie readData, zoals eerder uitgelegd;
  • De variabele postIndex slaat de index op van de post die moet worden bijgewerkt in de data array door de post-ID's te vergelijken;
  • Als de post niet wordt gevonden (d.w.z. postIndex === -1), wordt een 404 (Niet Gevonden) response met een foutmelding naar de client gestuurd;
  • Om de postgegevens bij te werken, worden de bestaande postgegevens (...data[postIndex]) samengevoegd met de bijgewerkte gegevens (...updatedData). Hierdoor worden alleen de opgegeven velden bijgewerkt en blijft bestaande data behouden;
  • Tot slot wordt de bijgewerkte data array teruggeschreven naar het JSON-bestand om de wijzigingen in de post op te slaan.

Verzenden van een response

Na een succesvolle update van de post wordt een JSON-response naar de client gestuurd. De response bevat een statuscode 200 (OK), wat aangeeft dat de update is geslaagd, en de bijgewerkte postgegevens.

res.status(200).json(data[postIndex]);

Foutafhandeling

De routecode wordt omgeven door een try-catch-blok om mogelijke fouten tijdens het ophalen van gegevens of het verwerken van verzoeken af te handelen. Eventuele fouten die zich voordoen, worden gelogd naar de console voor foutopsporing:

try {
  // ... (code for retrieving and processing data)
} catch (error) {
  console.error(error.message);
}

Volledige code van het postsRoutes.js-bestand in deze stap

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

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 4. Hoofdstuk 8

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Suggested prompts:

Can you explain how the validatePostData middleware works?

What should I do if I get a "Post not found" error when updating?

Can you show how to test the update route with an example request?

Awesome!

Completion rate improved to 2.56

bookHet Bouwen van de Update-Post-op-Id-Endpoint

Veeg om het menu te tonen

We onderzoeken hoe een bestaande post kan worden bijgewerkt met behulp van de "UPDATE POST BY ID"-route in het bestand postsRoutes.js. Deze route verwerkt het bijwerken van een post op basis van zijn unieke ID.

Routedefinitie

De onderstaande code definieert de "UPDATE POST BY ID"-route met behulp van router.put():

router.put("/post/:id", validatePostData, async (req, res, next) => { ... }
  • Deze route is geconfigureerd om HTTP PUT-verzoeken af te handelen, specifiek voor het bijwerken van posts;
  • Er is een geparameteriseerde :id in het routepad opgenomen om de bij te werken post te identificeren;
  • De middleware validatePostData is toegevoegd om gegevensvalidatie te waarborgen voordat wordt doorgegaan. De logica van de middleware validatePostData blijft hetzelfde als in de vorige stap.

Gegevens verkrijgen uit het verzoek

Hier worden de benodigde gegevens uit het verzoek gehaald, waaronder de post-ID en de bijgewerkte inhoud van de post:

const postId = req.params.id;
const updatedData = {
  username: req.body.username,
  postTitle: req.body.postTitle,
  postContent: req.body.postContent,
};
  • De post-ID wordt uit de request parameters gehaald, zodat deze beschikbaar is voor verdere verwerking. De :id parameter uit de route-URL wordt opgehaald met req.params.id;
  • De username, postTitle en postContent worden uit de body van het verzoek gehaald.

Post bijwerken in de database

Het bijwerken van een bestaande post omvat verschillende stappen, zoals hieronder beschreven:

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));
  • De bestaande gegevens worden uit het JSON-bestand gelezen met de asynchrone functie readData, zoals eerder uitgelegd;
  • De variabele postIndex slaat de index op van de post die moet worden bijgewerkt in de data array door de post-ID's te vergelijken;
  • Als de post niet wordt gevonden (d.w.z. postIndex === -1), wordt een 404 (Niet Gevonden) response met een foutmelding naar de client gestuurd;
  • Om de postgegevens bij te werken, worden de bestaande postgegevens (...data[postIndex]) samengevoegd met de bijgewerkte gegevens (...updatedData). Hierdoor worden alleen de opgegeven velden bijgewerkt en blijft bestaande data behouden;
  • Tot slot wordt de bijgewerkte data array teruggeschreven naar het JSON-bestand om de wijzigingen in de post op te slaan.

Verzenden van een response

Na een succesvolle update van de post wordt een JSON-response naar de client gestuurd. De response bevat een statuscode 200 (OK), wat aangeeft dat de update is geslaagd, en de bijgewerkte postgegevens.

res.status(200).json(data[postIndex]);

Foutafhandeling

De routecode wordt omgeven door een try-catch-blok om mogelijke fouten tijdens het ophalen van gegevens of het verwerken van verzoeken af te handelen. Eventuele fouten die zich voordoen, worden gelogd naar de console voor foutopsporing:

try {
  // ... (code for retrieving and processing data)
} catch (error) {
  console.error(error.message);
}

Volledige code van het postsRoutes.js-bestand in deze stap

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

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 4. Hoofdstuk 8
some-alt