Creación del Endpoint Post para Create
Examinaremos la creación de una nueva publicación utilizando la ruta "CREATE POST" dentro del archivo postsRoutes.js. Esta ruta se encarga de gestionar la creación de una publicación y guardarla en la fuente de datos (database/posts.json).
Definición de la Ruta
El siguiente código define la ruta "CREATE POST" utilizando router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Esta ruta está configurada para gestionar solicitudes HTTP POST en la ruta raíz
/; - Utiliza el middleware
validatePostData, que garantiza que los datos enviados en el cuerpo de la solicitud sean válidos antes de continuar.
Middleware de validación de datos
Antes de profundizar en la lógica de la ruta, es necesario crear un middleware de validación de datos. Este middleware garantiza que los datos enviados en el cuerpo de la solicitud sean válidos antes de intentar crear una nueva publicación.
// 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 función
validatePostDataextraeusername,postTitleypostContentdel cuerpo de la solicitud; - Verifica si estos campos están presentes. Si alguno de ellos falta (
!username,!postTitleo!postContent), responde con un código de estado 400 (Bad Request) y un mensaje de error indicando que faltan campos obligatorios; - Si los datos son válidos, el middleware llama a
next(), permitiendo que la solicitud continúe hacia el manejador de la ruta (en este caso, la ruta "CREATE POST").
Con el middleware de validación de datos implementado, continuemos con la lógica de la ruta "CREATE POST".
Datos de la nueva publicación
Para crear una nueva publicación, se genera un ID único utilizando Date.now().toString(). Además, se extraen username, postTitle y postContent del cuerpo de la solicitud.
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
Agregar la nueva publicación a la base de datos
Los siguientes pasos detallan cómo se agrega la nueva publicación a la base de datos:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Los datos existentes se leen del archivo JSON utilizando la función asíncrona
readData, como se explicó anteriormente; - La nueva publicación se agrega al arreglo
data; - El arreglo
dataactualizado se escribe nuevamente en el archivo JSON para guardar la publicación recién creada.
Envío de una respuesta
Tras la creación exitosa de la nueva publicación, se envía una respuesta de éxito al cliente. La respuesta incluye un código de estado 201 (Created) y los detalles de la publicación recién creada en formato JSON.
res.status(201).json(newPost);
Manejo de errores
El código de la ruta se envuelve en un bloque try-catch para gestionar posibles errores durante la recuperación de datos o el procesamiento de la solicitud. Cualquier error que ocurra se registra en la consola para fines de depuración:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Complete code of the postsRoutes.js file at this step
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);
}
});
Código completo del archivo 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;
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Awesome!
Completion rate improved to 2.56
Creación del Endpoint Post para Create
Desliza para mostrar el menú
Examinaremos la creación de una nueva publicación utilizando la ruta "CREATE POST" dentro del archivo postsRoutes.js. Esta ruta se encarga de gestionar la creación de una publicación y guardarla en la fuente de datos (database/posts.json).
Definición de la Ruta
El siguiente código define la ruta "CREATE POST" utilizando router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Esta ruta está configurada para gestionar solicitudes HTTP POST en la ruta raíz
/; - Utiliza el middleware
validatePostData, que garantiza que los datos enviados en el cuerpo de la solicitud sean válidos antes de continuar.
Middleware de validación de datos
Antes de profundizar en la lógica de la ruta, es necesario crear un middleware de validación de datos. Este middleware garantiza que los datos enviados en el cuerpo de la solicitud sean válidos antes de intentar crear una nueva publicación.
// 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 función
validatePostDataextraeusername,postTitleypostContentdel cuerpo de la solicitud; - Verifica si estos campos están presentes. Si alguno de ellos falta (
!username,!postTitleo!postContent), responde con un código de estado 400 (Bad Request) y un mensaje de error indicando que faltan campos obligatorios; - Si los datos son válidos, el middleware llama a
next(), permitiendo que la solicitud continúe hacia el manejador de la ruta (en este caso, la ruta "CREATE POST").
Con el middleware de validación de datos implementado, continuemos con la lógica de la ruta "CREATE POST".
Datos de la nueva publicación
Para crear una nueva publicación, se genera un ID único utilizando Date.now().toString(). Además, se extraen username, postTitle y postContent del cuerpo de la solicitud.
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
Agregar la nueva publicación a la base de datos
Los siguientes pasos detallan cómo se agrega la nueva publicación a la base de datos:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Los datos existentes se leen del archivo JSON utilizando la función asíncrona
readData, como se explicó anteriormente; - La nueva publicación se agrega al arreglo
data; - El arreglo
dataactualizado se escribe nuevamente en el archivo JSON para guardar la publicación recién creada.
Envío de una respuesta
Tras la creación exitosa de la nueva publicación, se envía una respuesta de éxito al cliente. La respuesta incluye un código de estado 201 (Created) y los detalles de la publicación recién creada en formato JSON.
res.status(201).json(newPost);
Manejo de errores
El código de la ruta se envuelve en un bloque try-catch para gestionar posibles errores durante la recuperación de datos o el procesamiento de la solicitud. Cualquier error que ocurra se registra en la consola para fines de depuración:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Complete code of the postsRoutes.js file at this step
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);
}
});
Código completo del archivo 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;
¡Gracias por tus comentarios!