I recently came across an interesting problem that I cannot solve for the life of me. I am calling an API call that is breaking up records into pages, the info for the pages reside in the response header. From that, I wanted to be able to do another call to retrieve the data and the next header, until there are no more response headers.
let parents = {};
const options = {
credentials: "same-origin",
headers: {
accept: "application/json"
},
timeout: 5000
};
fetch(
`/api/v1/courses/200003/enrollments?enrollment_type=ObserverEnrollment&per_page=100`,
options
).then(response =>
response
.json()
.then(data => ({
data: data,
ok: response.ok,
headers: response.headers
}))
.then(res => {
parents = res;
nextURL(res.headers.get("Link"));
let optionsNext = {
credentials: "same-origin",
headers: {
accept: "application/json"
},
timeout: 5000
};
fetch(nextURL(res.headers.get("Link")), optionsNext).then(response =>
response
.json()
.then(data => ({
data: data,
ok: response.ok,
headers: response.headers
}))
.then(res => {
if (res.ok) {
parents.data.push(res.data);
console.info(parents);
}
})
);
})
);
function nextURL(linkTxt) {
let url = null;
if (linkTxt) {
let links = linkTxt.split(",");
let nextRegEx = new RegExp('^<(.*)>; rel="next"$');
for (let i = 0; i < links.length; i++) {
let matches = nextRegEx.exec(links[i]);
if (matches) {
url = matches[1];
}
}
}
return url;
}
The part that I need to put into some kind of loop is the secondary fetch based upon the return of the nextURL function: if !nextURL(res.headers.get("Link")) I need to break the loop.
let optionsNext = {
credentials: "same-origin",
headers: {
accept: "application/json"
},
timeout: 5000
};
fetch(nextURL(res.headers.get("Link")), optionsNext).then(response =>
response
.json()
.then(data => ({
data: data,
ok: response.ok,
headers: response.headers
}))
.then(res => {
if (res.ok) {
parents.data.push(res.data);
console.info(parents);
}
})
);
Thanks in advance for even looking at my pitiful problem
fetchresolves, check if there's a next page, if there is, rerun the function. You really just need a dispatcher object so that you can call the fetch method recursively.