Skip to content

Commit

Permalink
Have at least one total_pages in case of empty query result (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
0237h authored May 9, 2024
1 parent b7a7b10 commit 9e05168
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/fetch/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
13 changes: 6 additions & 7 deletions src/fetch/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ 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) {
const api_error: APIError = {
status,
code: code ? code : "unknown",
detail: detail ? detail : ""
}
};

logger.error("<APIError>\n", api_error);
prometheus.request_error.inc({ pathname, status });
Expand All @@ -25,12 +25,11 @@ 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') {
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,
Expand All @@ -41,13 +40,13 @@ export function addMetadata(response: Query<any>, req_limit?: number, req_page?:
total_pages,
total_results: response.rows_before_limit_at_least
}
}
};
} else {
return {
data: response.data,
meta: {
statistics: response.statistics,
}
}
};
}
}

0 comments on commit 9e05168

Please sign in to comment.