API with Mongo Express and Node (the sequel)
I was creating the waiter who will connect the back-end of the application to the front-end. The link to the exciting prequel is below.
The Model...
The model refers to the way the database JSON file will look like based on the user specification.
First, we require mongoose and describe the schema as an object with the 'fields' title and post. Both fields will be required by the database to be filled and the API will make sure of it.
The Routes...
In many ways (pun intended), the routes provide the basis for the API as it shows the methods to be used to create, retrieve, update and delete the data. Through the use of the HTTP request methods, the CRUD functionalities are achieved. The HTTP request methods include GET, PATCH or PUT and POST. The actions are applied at specific endpoints. Firstly, we should create an instance of the express router and assigning it to the constant router so as to use it as the middle-ware. The router object is chained together with the API endpoint.
router.HTTP Method(path, handler function)
The first GET HTTP method is used return a JSON array of the blog posts found in the database we created. Next we get request to the path of posts with the specific id so that to go to specific blog posts. If the blog post is not found, am error message is displayed.
The Post request creates a new instance of a blog post based on the structure of the model we had created. The database automatically assigns an ID to the new blog post. Successful save will be seen using status 200. The Patch requests takes the path of the specific post and the handler function is used to change the payload. In case of failure, the response 422 is returned to the user, otherwise a JSON response of successful updating.
The Delete requests firsts checks to see if the specific post exists and if it exists, proceeds to delete it. When you restart your server and go to https://localhost:5000/api/blogposts you should see an empty array. If you use apps like postman, mongodb compass and curl you can test to see if your endpoints are working.
That's all folks! I hope it can be clearly understood. Feel free to correct, add or comment on both posts.