here is how I implemented it. In this case the api is returning a ndjson as a stream (which is what lichess also does on some endpoints). I am reading the stream in chunks with a reader. In ndjson format, data is split by new lines, so each line by itself is a basic json which I parsed and added to fetchedData variable.
var fetchedData = [];
fetch('LinkGoesHere', {
method: 'get',
headers: {
'Authorization': 'Bearer TokenGoesHere' // this part is irrelevant and you may not need it for your application
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.body.getReader();
})
.then(reader => {
let partialData = '';
// Read and process the NDJSON response
return reader.read().then(function processResult(result) {
if (result.done) {
return;
}
partialData += new TextDecoder().decode(result.value, { stream: true });
const lines = partialData.split('\n');
for (let i = 0; i < lines.length - 1; i++) {
const json = JSON.parse(lines[i]);
fetchedData.push(json); // Store the parsed JSON object in the array
}
partialData = lines[lines.length - 1];
return reader.read().then(processResult);
});
})
.then(() => {
// At this point, fetchedData contains all the parsed JSON objects
console.log(fetchedData);
})
.catch(error => {
console.error('Fetch error:', error);
});