Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Creazione dell'Endpoint Post Create | Creazione di API REST con Node.js ed Express.js
Sviluppo Backend con Node.js ed Express.js

bookCreazione dell'Endpoint Post Create

Esamineremo la creazione di un nuovo post utilizzando la rotta "CREATE POST" all'interno del file postsRoutes.js. Questa rotta è responsabile della gestione della creazione di un post e del suo salvataggio nella fonte dati (database/posts.json).

Definizione della rotta

Il codice seguente definisce la rotta "CREATE POST" utilizzando router.post():

router.post("/", validatePostData, async (req, res, next) => { ... }
  • Questa rotta è configurata per gestire le richieste HTTP POST al percorso radice /;
  • Utilizza il middleware validatePostData, che garantisce la validità dei dati inviati nel corpo della richiesta prima di procedere.

Middleware di Validazione dei Dati

Prima di approfondire la logica della route, è necessario creare un middleware di validazione dei dati. Questo middleware garantisce che i dati inviati nel corpo della richiesta siano validi prima di tentare di creare un nuovo post.

// Middleware to validate post data
function validatePostData(req, res, next) {
  const { username, postTitle, postContent } = req.body;

  if (!username || !postTitle || !postContent) {
    return res.status(400).json({ error: "Missing required fields" });
  }

  // If data is valid, proceed to the next route handler
  next();
}
  • La funzione validatePostData estrae username, postTitle e postContent dal corpo della richiesta;
  • Verifica che questi campi siano presenti. Se uno di essi manca (!username, !postTitle o !postContent), risponde con un codice di stato 400 (Bad Request) e un messaggio di errore che indica i campi obbligatori mancanti;
  • Se i dati sono validi, il middleware chiama next(), consentendo alla richiesta di proseguire verso il gestore della route (in questo caso la route "CREATE POST").

Con il middleware di validazione dei dati implementato, si può proseguire con la logica della route "CREATE POST".

Dati del Nuovo Post

Per creare un nuovo post, viene generato un ID univoco utilizzando Date.now().toString(). Inoltre, vengono estratti username, postTitle e postContent dal corpo della richiesta.

const newPost = {
  id: Date.now().toString(),
  username: req.body.username,
  postTitle: req.body.postTitle,
  postContent: req.body.postContent,
};

Aggiunta del Nuovo Post al Database

I seguenti passaggi illustrano come il nuovo post viene aggiunto al database:

const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
  • I dati esistenti vengono letti dal file JSON utilizzando la funzione asincrona readData, come spiegato in precedenza;
  • Il nuovo post viene aggiunto all'array data;
  • L'array data aggiornato viene quindi riscritto nel file JSON per salvare il nuovo post creato.

Invio di una risposta

Al termine della creazione del nuovo post, viene inviata una risposta di successo al client. La risposta include un codice di stato 201 (Created) e i dettagli del nuovo post creato in formato JSON.

res.status(201).json(newPost);

Gestione degli errori

Il codice della route viene racchiuso in un blocco try-catch per gestire eventuali errori durante il recupero dei dati o l'elaborazione della richiesta. Gli errori che si verificano vengono registrati nella console per scopi di debug:

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

Codice completo del file postsRoutes.js in questo passaggio

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 {
    // Generate a unique ID for the new post
    const newPost = {
      id: Date.now().toString(),
      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);
  }
});

Codice completo del file validateData.js

// Middleware to validate post data
function validatePostData(req, res, next) {
  const { username, postTitle, postContent } = req.body;

  if (!username || !postTitle || !postContent) {
    return res.status(400).json({ error: "Missing required fields" });
  }

  // If data is valid, proceed to the next route handler
  next();
}

module.exports = validatePostData;

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 7

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Awesome!

Completion rate improved to 2.56

bookCreazione dell'Endpoint Post Create

Scorri per mostrare il menu

Esamineremo la creazione di un nuovo post utilizzando la rotta "CREATE POST" all'interno del file postsRoutes.js. Questa rotta è responsabile della gestione della creazione di un post e del suo salvataggio nella fonte dati (database/posts.json).

Definizione della rotta

Il codice seguente definisce la rotta "CREATE POST" utilizzando router.post():

router.post("/", validatePostData, async (req, res, next) => { ... }
  • Questa rotta è configurata per gestire le richieste HTTP POST al percorso radice /;
  • Utilizza il middleware validatePostData, che garantisce la validità dei dati inviati nel corpo della richiesta prima di procedere.

Middleware di Validazione dei Dati

Prima di approfondire la logica della route, è necessario creare un middleware di validazione dei dati. Questo middleware garantisce che i dati inviati nel corpo della richiesta siano validi prima di tentare di creare un nuovo post.

// Middleware to validate post data
function validatePostData(req, res, next) {
  const { username, postTitle, postContent } = req.body;

  if (!username || !postTitle || !postContent) {
    return res.status(400).json({ error: "Missing required fields" });
  }

  // If data is valid, proceed to the next route handler
  next();
}
  • La funzione validatePostData estrae username, postTitle e postContent dal corpo della richiesta;
  • Verifica che questi campi siano presenti. Se uno di essi manca (!username, !postTitle o !postContent), risponde con un codice di stato 400 (Bad Request) e un messaggio di errore che indica i campi obbligatori mancanti;
  • Se i dati sono validi, il middleware chiama next(), consentendo alla richiesta di proseguire verso il gestore della route (in questo caso la route "CREATE POST").

Con il middleware di validazione dei dati implementato, si può proseguire con la logica della route "CREATE POST".

Dati del Nuovo Post

Per creare un nuovo post, viene generato un ID univoco utilizzando Date.now().toString(). Inoltre, vengono estratti username, postTitle e postContent dal corpo della richiesta.

const newPost = {
  id: Date.now().toString(),
  username: req.body.username,
  postTitle: req.body.postTitle,
  postContent: req.body.postContent,
};

Aggiunta del Nuovo Post al Database

I seguenti passaggi illustrano come il nuovo post viene aggiunto al database:

const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
  • I dati esistenti vengono letti dal file JSON utilizzando la funzione asincrona readData, come spiegato in precedenza;
  • Il nuovo post viene aggiunto all'array data;
  • L'array data aggiornato viene quindi riscritto nel file JSON per salvare il nuovo post creato.

Invio di una risposta

Al termine della creazione del nuovo post, viene inviata una risposta di successo al client. La risposta include un codice di stato 201 (Created) e i dettagli del nuovo post creato in formato JSON.

res.status(201).json(newPost);

Gestione degli errori

Il codice della route viene racchiuso in un blocco try-catch per gestire eventuali errori durante il recupero dei dati o l'elaborazione della richiesta. Gli errori che si verificano vengono registrati nella console per scopi di debug:

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

Codice completo del file postsRoutes.js in questo passaggio

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 {
    // Generate a unique ID for the new post
    const newPost = {
      id: Date.now().toString(),
      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);
  }
});

Codice completo del file validateData.js

// Middleware to validate post data
function validatePostData(req, res, next) {
  const { username, postTitle, postContent } = req.body;

  if (!username || !postTitle || !postContent) {
    return res.status(400).json({ error: "Missing required fields" });
  }

  // If data is valid, proceed to the next route handler
  next();
}

module.exports = validatePostData;

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 7
some-alt