43 lines
1.4 KiB
TypeScript
43 lines
1.4 KiB
TypeScript
import { postgrestLocalUrl } from "./constants";
|
|
|
|
/*
|
|
* https://postgrest.org/en/latest/references/api/pagination_count.html
|
|
* HTTP/1.1 206 Partial Content
|
|
* Content-Range: 0-24/3572000
|
|
*/
|
|
export function getCountFromHeaders(res: Response) {
|
|
const count = parseInt(res.headers.get('Content-Range')?.split('/').at(-1) || '0')
|
|
return count
|
|
}
|
|
|
|
export async function fetchPaginatedData(apiEndpoint: string, pageSize: number, queryParams: Record<string, any> = {}): Promise<any[]> {
|
|
let data: any[] = [];
|
|
let totalDataCount: number = 0;
|
|
let totalRequestsNeeded: number = 1;
|
|
|
|
for (let requestCounter = 0; requestCounter < totalRequestsNeeded; requestCounter++) {
|
|
const humanReadableRequestCount = requestCounter + 1;
|
|
const params = new URLSearchParams({
|
|
'pagination[page]': humanReadableRequestCount.toString(),
|
|
'pagination[pageSize]': pageSize.toString(),
|
|
...queryParams,
|
|
});
|
|
const url = `${postgrestLocalUrl}${apiEndpoint}?${params}`;
|
|
|
|
const response = await fetch(url, {
|
|
method: 'GET'
|
|
});
|
|
|
|
const responseData = await response.json();
|
|
|
|
|
|
if (requestCounter === 0) {
|
|
totalDataCount = responseData.meta.pagination.total;
|
|
totalRequestsNeeded = Math.ceil(totalDataCount / pageSize);
|
|
}
|
|
data = data.concat(responseData.data);
|
|
}
|
|
|
|
return data;
|
|
}
|