Course Content
Node.js Express: API & CLI Apps
Node.js Express: API & CLI Apps
Implementing the "CREATE POST" Route
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()
:
- 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.
- 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.
Add the New Post to the Database
The following steps detail how the new post is added to the database:
- 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.
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:
Complete code of the postsRoutes.js file at this step
Complete code of the validateData.js file
Thanks for your feedback!