I am in the process of extracting all names from an API that provides a JSON response structured like this:
{
"data" : [
{
"attributes" : {
"name" : "Prog1"
...
},
"id" : "12345",
},
{
"attributes" : {
"name" : "Prog2"
...
},
"id" : "67890",
},
...
],
"links" : {
"next" : "https://api.company.com/v1/programs?page%5Bnumber%5D=3",
"self" : "https://api.company.com/v1/programs?page%5Bnumber%5D=2",
"prev" : "https://api.company.com/v1/programs?page%5Bnumber%5D=1",
}
}
The goal is to continue making requests and recording the names until no more "next" link is available, at which point the process should stop.
Presented below is the current function:
async function getPrograms(url: string, user: string, pass: string) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {Authorization: 'Basic ' + Buffer.from(`${user}:${pass}`).toString('base64')},
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
console.log(response);
const result = (await response.json()) as GetProgramsResponse;
result.data.forEach((program) => {
// More functionality will be added here
console.log(program.attributes.name);
})
console.log(result.links.next);
if (result.links.next) {
getPrograms(result.links.next, user, pass)
}
} catch (error) {
if (error instanceof Error) {
console.log('error message: ', error.message);
return error.message;
} else {
console.log('unexpected error: ', error);
return 'An unexpected error occured';
}
}
};
getPrograms(url, u, p);
It seems like the program stops progressing after about 6 iterations without completing the task. It's likely due to the asynchronous nature of the requests, but I'm unsure how to handle waiting for all iterations to finish since I'm still learning TypeScript.
I welcome guidance on resolving this issue and any feedback on the overall proposed solution.
Thank you!