Created
June 27, 2016 08:23
-
-
Save catkins/df466c3fed0ccf45aa5fff1067feefb8 to your computer and use it in GitHub Desktop.
swapi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// takes array and returns hash keyed by property | |
const indexBy = (array, property) => array.reduce((hash, item) => { | |
hash[item[property]] = item | |
return hash; | |
}, {}) | |
const get = async function (url) { | |
// force https on Star Wars API | |
const httpsUrl = url.replace('http://', 'https://') | |
const response = await fetch(httpsUrl) | |
const json = await response.json() | |
return json | |
} | |
let fetchAllFromResource = async function (resource) { | |
let page = await get(resource) | |
let records = page.results | |
while (page.next) { | |
page = await get(page.next) | |
records.push(...page.results) | |
} | |
return records; | |
} | |
// get(resource).then(page => { | |
// }) | |
const main = async function () { | |
try { | |
const root = await get('https://swapi.co/api/') | |
// const species = await fetchAllFromResource(root.species) | |
// const characters = await fetchAllFromResource(root.people) | |
// Can do it at the same time! | |
const [ species, characters] = await Promise.all([ | |
fetchAllFromResource(root.species), | |
fetchAllFromResource(root.people) | |
]) | |
const speciesMap = indexBy(species, 'url') | |
const bios = characters.map(character => { | |
const species = speciesMap[character.species[0]] | |
if (species) { | |
return `${character.name} is a ${species.name}` | |
} else { | |
return `${character.name} is an unknown species` | |
} | |
}) | |
alert(bios) | |
} catch (error) { | |
debugger | |
alert(error) | |
} | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment