diff --git a/src/fetch/utils.spec.ts b/src/fetch/utils.spec.ts index 51f6588..a9986a3 100644 --- a/src/fetch/utils.spec.ts +++ b/src/fetch/utils.spec.ts @@ -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", () => { diff --git a/src/fetch/utils.ts b/src/fetch/utils.ts index 3d141b1..56856d4 100644 --- a/src/fetch/utils.ts +++ b/src/fetch/utils.ts @@ -26,22 +26,28 @@ export function toJSON(data: any, status: number = 200) { export function addMetadata(response: Query, 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, } } + } } \ No newline at end of file