Skip to content

Commit

Permalink
✨ get total results for results with more than 9 pages
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Meischner committed Oct 4, 2021
1 parent 80e70c5 commit 45055cf
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 13 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"typescript-tslint-plugin": "^1.0.1"
},
"dependencies": {
"node-fetch": "^3.0.0"
"node-fetch": "^2.6.0"
},
"files": [
"lib/**/*"
Expand Down
1 change: 1 addition & 0 deletions src/clickout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export class ClickoutRequestBuilder {
constructor() {
this.request = {
last_clicks: null,
page: 1,
};
}

Expand Down
1 change: 1 addition & 0 deletions src/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export class TransactionRequestBuilder {
date_type: null,
end_date: null,
start_date: null,
page: 1,
status: [],
};
}
Expand Down
35 changes: 23 additions & 12 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,32 @@ export async function getAllPages<T extends GeneralResponseData>(
): Promise<T['data']> {
try {
const firstPage = await getSinglePage(request, endpoint, key);
const pages = await Promise.all(
firstPage.links
.filter((l) => parseInt(l.label, 10) && parseInt(l.label, 10) > 1)
.map(async (l): Promise<T> => {
const page = await fetch(l.url, {
headers: {
'X-API-Key': key,
},
});
return (await page.json()) as T;
let result = null;
if (isPageRequest(request)) {
const nrOfPages = firstPage.last_page;
const pages = await Promise.all(
range(2, nrOfPages).map(async (l): Promise<T> => {
const req = Object.assign({}, request) as object & { page: number };
req.page = l;
return await getSinglePage(req, endpoint, key);
}),
);
const result = firstPage.data.concat(...pages.map((p) => p.data)) as T['data'];
);
result = firstPage.data.concat(...pages.map((p) => p.data)) as T['data'];
} else {
result = firstPage.data as T['data'];
}
return result;
} catch (e) {
error('It was not possible to fetch all pages', e);
}
}

const range = (start: number, end: number): number[] => {
return Array(end - start + 1)
.fill(0)
.map((_, idx) => start + idx);
};

const isPageRequest = (request: object): boolean => {
return Object.keys(request).includes('page');
};

0 comments on commit 45055cf

Please sign in to comment.