From 9e05168ceebfc5b54968b397ed277e26d3262559 Mon Sep 17 00:00:00 2001 From: Etienne Donneger Date: Thu, 9 May 2024 16:32:40 -0400 Subject: [PATCH] Have at least one `total_pages` in case of empty query result (#28) --- src/fetch/utils.spec.ts | 2 +- src/fetch/utils.ts | 13 ++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/fetch/utils.spec.ts b/src/fetch/utils.spec.ts index a9986a3..fe1f8f9 100644 --- a/src/fetch/utils.spec.ts +++ b/src/fetch/utils.spec.ts @@ -42,7 +42,7 @@ test("addMetadata pagination", () => { expect(last_page.meta.total_results).toBe(5 * limit); // Expect error message on beyond last page - expect(() => addMetadata(mock_query_reponse, limit, limit + 1)).toThrow("Requested page exceeds total pages"); + expect(() => addMetadata(mock_query_reponse, limit, limit + 1)).toThrow(`Requested page (${limit + 1}) exceeds total pages (${limit})`); }); test("addMetadata no pagination", () => { diff --git a/src/fetch/utils.ts b/src/fetch/utils.ts index 56856d4..1cbf5af 100644 --- a/src/fetch/utils.ts +++ b/src/fetch/utils.ts @@ -5,7 +5,7 @@ import * as prometheus from "../prometheus.js"; interface APIError { status: number, code?: string, - detail?: string + detail?: string; } export function APIError(pathname: string, status: number, code?: string, detail?: string) { @@ -13,7 +13,7 @@ export function APIError(pathname: string, status: number, code?: string, detail status, code: code ? code : "unknown", detail: detail ? detail : "" - } + }; logger.error("\n", api_error); prometheus.request_error.inc({ pathname, status }); @@ -25,12 +25,11 @@ 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') { - const total_pages = Math.ceil(response.rows_before_limit_at_least / req_limit); + const total_pages = Math.max(Math.ceil(response.rows_before_limit_at_least / req_limit), 1); // Always have a least one total page if (req_page > total_pages) - throw Error("Requested page exceeds total pages") + throw Error(`Requested page (${req_page}) exceeds total pages (${total_pages})`); return { data: response.data, @@ -41,13 +40,13 @@ export function addMetadata(response: Query, req_limit?: number, req_page?: total_pages, total_results: response.rows_before_limit_at_least } - } + }; } else { return { data: response.data, meta: { statistics: response.statistics, } - } + }; } } \ No newline at end of file