I'm using the Selly API and trying to fetch all products, however the Selly API paginates products.
So I need to fetch all products and add to an array and then output the result via JSON.
const base64 = require('base-64');
import fetch from 'isomorphic-unfetch';
export default async (req, res) => {
res.setHeader('Content-Type', 'application/json');
try {
request('products')
.then(data => data.json())
.then(json => res.status(200).end(JSON.stringify(json)));
} catch(err) {
res.end(JSON.stringify({
"error": err
}));
}
}
const getToken = () => {
return base64.encode(`${process.env.api.email}:${process.env.api.key}`);
}
const request = async (endpoint = '', page) => {
const options = {
headers: {
Authorization: `Basic ${getToken()}`,
'User-Agent': `${process.env.api.email} - https://example.com`
}
}
return fetch(`https://selly.io/api/v2/${endpoint}?page=${page}`, options);
}
I'm trying to fetch https://selly.io/api/v2/products?page=${page} until the return result is an empty array [].
My attempt was this:
const repeatedRequest = async (data, endpoint) => {
let i = 1;
while (data.length > 0) {
console.log(data);
await request(endpoint, i).then((res) => {
data.push(res);
i++;
});
}
return data;
}
However this didn't work because the return result was an empty array. I am also confused how I would do this along with the following snippet:
request('products')
.then(data => data.json())
.then(json => res.status(200).end(JSON.stringify(json)));
How would I work in the function into this?
How can I do this?
while (data.length >0) /*push something into data*/. That seems like an endless loop, assuming it ever gets started.datawill only ever get longer, right? I don't see howdata.lengthmight become 0. I was expecting an exit condition where the request detects failure (mayberesis undefined in this case?) and then have that cause the loop to exit (probably just cause it to return when res is undefined.) Or do I misunderstand?data.lengthwill always be greater than 0, assuming it starts nonempty (and if it starts out empty, the loop will never run at all). It seems you want to check if the actual API responsereshas length 0, instead ofdata, which is where you are accumulating all of the responses.console.loginside thewhileloop - when you run it, does it print anything out?