Использование fetch
.Существует свойство link
Header, которое сообщает вам next
, prev
и last
URL-адреса конечной точки, которую вы просматриваете.
Вы должны объединять / упорядочивать запросы таким образом, чтобыВы получаете первый URL, получаете URL next
и делаете вызов на следующую страницу.Продолжайте делать это до тех пор, пока у вас не закончатся страницы и вы не соберете все символы таким образом.
Я заметил, что не у всех есть name
, поэтому я выбираю либо имя, либо первый псевдоним.
Также, чтобы облегчить доступ к серверу, я ограничил глубину процесса до 3 запросов.Вы должны удалить это, если вы не хотите лимит.
function parseHeaders(res) {
return res.headers.get("link").split(",").reduce((acc, link) => {
const props = /^\<(.+)\>; rel="(.+)"$/.exec(link.trim());
if (!props) {
console.warn("no match");
return acc;
}
acc[props[2]] = props[1];
return acc;
}, {});
}
async function go(url, depth = 0) {
/*
* You don't need this, this is just to alleviate load on the API's server
* You should remove all the stuff about depth whenever you use this,
* it just limits the total number of requests to fire to 3 which is nice
* since it looks like there would be like 215 requests if you didn't do this.
*/
if (depth >= 3) return [];
const res = await fetch(url);
const props = parseHeaders(res);
const data = await res.json();
const characters = data.map(character => character.name || character.aliases[0]);
if (props.next) {
const newCharacters = await go(props.next, depth + 1);
characters.push(...newCharacters);
}
return characters;
}
(async function() {
const characters = await go("https://www.anapioficeandfire.com/api/characters");
console.log(characters);
}());