Creazione dell'Endpoint GET per Tutti i Post
Scorri per mostrare il menu
Esplorazione dell'implementazione della rotta "GET ALL POSTS" nel file postsRoutes.js. Questa rotta recupera un elenco di tutti i post dalla fonte dati (database/posts.json) e li invia come risposta al client.
Importazione dei moduli e delle dipendenze necessari
All'inizio del file vengono importati i moduli e le dipendenze richiesti:
const express = require("express");
const fs = require("fs/promises");
const validatePostData = require("../middlewares/validateData");
express: Importazione del framework Express per la creazione delle rotte;fs/promises: Modulo che fornisce operazioni asincrone sui file, utilizzato per leggere i dati da un file JSON;validatePostData: Anche se non utilizzato in questa rotta, viene importato il middlewarevalidatePostData, utile per la validazione dei dati nei capitoli successivi.
Inizializzazione di un Router Express
Inizializzazione di un'istanza di router Express, responsabile della gestione di tutte le rotte definite in questo file:
const router = express.Router();
Creazione di una funzione per la lettura dei dati
Definizione di una funzione asincrona chiamata readData per leggere i dati da un file JSON. Questa funzione garantisce il corretto recupero dei dati e gestisce eventuali errori:
// 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: Utilizzo difs.readFileper leggere il contenuto del file./database/posts.json;JSON.parse: I dati recuperati dal file vengono convertiti in un oggetto JavaScript;- Gestione degli errori: Eventuali errori durante la lettura o la conversione vengono intercettati e lanciati.
Definizione della rotta "GET ALL POSTS"
Definizione della rotta "GET ALL POSTS" all'interno del router:
// 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
}
});
Definizione della rotta: Specifica che questa rotta gestisce le richieste HTTP GET al percorso root (/).
Gestore della rotta: All'interno della funzione handler della rotta:
- Chiamata della funzione
readDataper recuperare l'elenco dei post dal file JSON; - In caso di successo, invio dei dati recuperati come risposta tramite
res.send(data); - In caso di errore durante il processo, intercettazione dell'errore, registrazione nel console per il debug (
console.error(error.message)) e prosecuzione.
Codice completo del file postsRoutes.js a 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
}
});
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione