Skip to content

Commit

Permalink
Throw error if the request page is beyond the total
Browse files Browse the repository at this point in the history
  • Loading branch information
0237h committed May 7, 2024
1 parent 3b49e36 commit a48fef2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
4 changes: 2 additions & 2 deletions src/fetch/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ test("addMetadata pagination", () => {
expect(last_page.meta.total_pages).toBe(5);
expect(last_page.meta.total_results).toBe(5 * limit);

// TODO: Expect error message on beyond last page
// const beyond_last_page = addMetadata(mock_query_reponse.data, mock_query_reponse.rows_before_limit_at_least, limit, 6);
// Expect error message on beyond last page
expect(() => addMetadata(mock_query_reponse, limit, limit + 1)).toThrow("Requested page exceeds total pages");
});

test("addMetadata no pagination", () => {
Expand Down
18 changes: 12 additions & 6 deletions src/fetch/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,28 @@ export function toJSON(data: any, status: number = 200) {

export function addMetadata(response: Query<any>, req_limit?: number, req_page?: number) {
// TODO: Catch page number greater than total_pages and return error
if (typeof (req_limit) !== 'undefined' && typeof (req_page) !== 'undefined')
if (typeof (req_limit) !== 'undefined' && typeof (req_page) !== 'undefined') {
const total_pages = Math.ceil(response.rows_before_limit_at_least / req_limit);

if (req_page > total_pages)
throw Error("Requested page exceeds total pages")

return {
data: response.data,
meta: {
statistics: response.statistics,
"next_page": (req_page * req_limit >= response.rows_before_limit_at_least) ? req_page : req_page + 1,
"previous_page": (req_page <= 1) ? req_page : req_page - 1,
"total_pages": Math.ceil(response.rows_before_limit_at_least / req_limit),
"total_results": response.rows_before_limit_at_least
next_page: (req_page * req_limit >= response.rows_before_limit_at_least) ? req_page : req_page + 1,
previous_page: (req_page <= 1) ? req_page : req_page - 1,
total_pages,
total_results: response.rows_before_limit_at_least
}
}
else
} else {
return {
data: response.data,
meta: {
statistics: response.statistics,
}
}
}
}

0 comments on commit a48fef2

Please sign in to comment.