Challenge: Build an API to Fetch Posts
Take the coding challenge to build an API using Express.js to fetch a set of random posts and apply middleware.
We'll cover the following
Problem statement
Below are the functions that needs to be implemented in order to finish the challenge. A code editor is provided after the problem statement to complete the coding challenge. Make sure all the points are implemented. After the coding challenge, there is a solution provided at the end.
Requirements
Implement the
fetchPosts()
function in theutils.js
file. Below are the requirements:The function will accept two parameters:
limit
andoffset
wherelimit
will tell how many posts need to be returned in the response andoffset
will tell from which position/index we need to start fetching the posts. Consider that there are a total of 100 posts. Now, in the first API call, we only want to fetch the first 10 posts (limit = 10 and offset = 0 since we need to start fetching from the first post itself). In the next API call, we want to fetch the next 10 posts (limit = 10 and offset = 10 since now we want to fetch from the 11th post which is indexed at 10 in a list). And the process continues.Make an API call to
https://jsonplaceholder.typicode.com/posts
usingaxios
. It will return a list of 100 posts. Process them so that each post has onlyid
,title
, andbody
and nothing else. Also, process them to accommodate thelimit
andoffset
given in the function params.Finally return the set of posts as per the
limit
,offset
, and require data for each post in a list.
Implement the
validateRequestMiddlewareFunction()
inmiddleware.js
file. Below are the requirements:Add a check on the request's query parameters that if there is no value sent for
limit
andoffset
, then set a default value of 10 and 0 tolimit
andoffset
respectively.Make sure the values for limit and offset are converted to integer since the query parameters are considered in string by default.
Implement the API route to fetch the posts in the
index.js
file. Below are the requirements:An endpoint
/fetch-posts
is already created and please do update the endpoint.Call the
fetchPosts()
function and make sure error-handling is implemented properly.In case of any error, return an object in the response containing
error
key and the error message as its value. Also, send the status code as 400.
Try it yourself
Below is the code block in which you can complete the coding challenge as per the requirements given.
Get hands-on with 1400+ tech skills courses.