Implement a backend pagination endpoint for a product catalog API using query parameters limit and page (or skip).
Background
The product catalog contains a mock dataset loaded in mockProducts.js. Currently, GET /api/products returns the entire dataset without any pagination or metadata validation, which causes high payload sizes and poor performance as the dataset grows.
Requirements
Modify app.js to update the GET /api/products endpoint to handle pagination using query parameters:
- Query Parameters:
-
limit (optional): The maximum number of products to return per page.
-
Default value: 10
-
Must be a positive integer ($> 0$).
-
Maximum allowed limit: 50. If a limit greater than 50 is provided, clamp/cap it to 50.
-
page (optional): The page number requested.
-
Default value: 1
-
Must be a positive integer ($> 0$).
-
Calculate zero-indexed skip/offset as: $\text{skip} = (\text{page} - 1) \times \text{limit}$.
-
Alternatively, allow an explicit skip query parameter:
-
If skip is provided directly in the query, use it over the computed page offset. skip must be a non-negative integer ($\ge 0$, default 0).
- Validation & Error Handling:
- If
limit, page, or skip parameters are provided but are invalid (e.g., non-numeric strings like "abc", negative numbers, or page/limit equal to 0), return HTTP status code 400 Bad Request with an error message:
{ "error": "Invalid pagination parameters" }
- Response Payload Structure:
The API must respond with HTTP status
200 and a structured JSON object containing:
{
"data": [ ...array of products for current page... ],
"pagination": {
"totalItems": 105,
"totalPages": 11,
"currentPage": 1,
"limit": 10,
"hasNextPage": true,
"hasPrevPage": false
}
}
Files to Edit
app.js — Implement pagination logic and parameter validations inside the GET /api/products handler.