generated from nhcarrigan/template
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* @copyright NHCarrigan
|
||||
* @license Naomi's Public License
|
||||
* @author Naomi Carrigan
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fetches a paginated resource from a URL. Automatically handles pagination,
|
||||
* and returns the complete data as an array.
|
||||
* @type {Array<Record<string, unknown>>} T - The type of data returned from the API endpoint. This should be an array of objects.
|
||||
* @param url - The URL to fetch.
|
||||
* @param limit - The number of items to fetch per page.
|
||||
* @param options - The standard fetch options object.
|
||||
* @returns The complete data as type T.
|
||||
*/
|
||||
export const paginatedFetch = async <T extends Array<Record<string, unknown>>>(
|
||||
url: string,
|
||||
limit: number,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> => {
|
||||
let page = 1;
|
||||
let offset = 0;
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- This is a workaround to avoid type errors.
|
||||
const data: T = [] as unknown as T;
|
||||
let request = await fetch(`${url}?limit=${limit.toString()}&page=${page.toString()}&offset=${offset.toString()}`, options);
|
||||
let response: T = await request.json();
|
||||
data.push(...response);
|
||||
while (response.length >= limit) {
|
||||
page = page + 1;
|
||||
offset = offset + limit;
|
||||
request = await fetch(`${url}?limit=${limit.toString()}&page=${page.toString()}&offset=${offset.toString()}`, options);
|
||||
response = await request.json();
|
||||
data.push(...response);
|
||||
}
|
||||
return data;
|
||||
};
|
||||
Reference in New Issue
Block a user