Building the CREATE Post Endpoint
We will examine creating a new post using the "CREATE POST" route within the postsRoutes.js
file. This route is responsible for handling the creation of a post and saving it to the data source (database/posts.json
).
Route Definition
The code below defines the "CREATE POST" route using router.post()
:
jsrouter.post("/", validatePostData, async (req, res, next) => { ... }
This route is configured to handle HTTP POST requests to the root path
/
;It utilizes the
validatePostData
middleware, which ensures that the data sent in the request body is valid before proceeding.
Data Validation Middleware
Before delving into the route's logic, we must create a data validation middleware. This middleware ensures that the data sent in the request body is valid before attempting to create a new post.
js991234567891011// Middleware to validate post datafunction 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 handlernext();}
The
validatePostData
function extracts theusername
,postTitle
, andpostContent
from the request body;It checks whether these fields are present. If any of them are missing (
!username
,!postTitle
, or!postContent
), it responds with a 400 (Bad Request) status code and an error message indicating missing required fields;If the data is valid, the middleware calls
next()
, allowing the request to continue to the route handler (the "CREATE POST" route in this case).
With the data validation middleware in place, let's continue with the "CREATE POST" route logic.
New Post Data
To create a new post, we generate a unique ID using Date.now().toString()
. Additionally, we extract the username
, postTitle
, and postContent
from the request body.
js9123456const newPost = {id: Date.now().toString(),username: req.body.username,postTitle: req.body.postTitle,postContent: req.body.postContent,};
Add the New Post to the Database
The following steps detail how the new post is added to the database:
js9123const data = await readData();data.push(newPost);await fs.writeFile("./database/posts.json", JSON.stringify(data));
The existing data is read from the JSON file using the asynchronous
readData
function, as previously explained;The new post is added to the
data
array;The updated
data
array is then written back to the JSON file to save the newly created post.
Sending a Response
Upon successful creation of the new post, a success response is sent to the client. The response includes a status code of 201 (Created) and the details of the newly created post in JSON format.
jsres.status(201).json(newPost);
Error Handling
We wrap the route code in a try-catch block to handle potential errors during data retrieval or request processing. Any errors that occur are logged to the console for debugging purposes:
js912345try {// ... (code for retrieving and processing data)} catch (error) {console.error(error.message);}
Complete code of the postsRoutes.js file at this step
js99123456789101112131415161718192021222324252627282930313233343536const express = require("express");const fs = require("fs/promises");const validatePostData = require("../middlewares/validateData");const router = express.Router();// Function to read data from the JSON fileasync function readData() {try {// Read the contents of the `posts.json` fileconst data = await fs.readFile("./database/posts.json");// Parse the JSON data into a JavaScript objectreturn JSON.parse(data);} catch (error) {// If an error occurs during reading or parsing, throw the errorthrow error;}}// GET ALL POSTSrouter.get("/", async (req, res, next) => {try {// Call the `readData` function to retrieve the list of postsconst data = await readData();// Send the retrieved data as the responseres.status(200).send(data);} catch (error) {// If an error occurs during data retrieval or sending the responseconsole.error(error.message); // Log the error to the console for debugging}});// GET POST BY IDrouter.get("/post/:id", async (req, res, next) => {try {// Extract the post ID from the request parameters
Complete code of the validateData.js file
js9912345678910111213// Middleware to validate post datafunction 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 handlernext();}module.exports = validatePostData;
Takk for tilbakemeldingene dine!
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår