Skip to content

Instantly share code, notes, and snippets.

@catkins
Created June 27, 2016 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save catkins/df466c3fed0ccf45aa5fff1067feefb8 to your computer and use it in GitHub Desktop.
Save catkins/df466c3fed0ccf45aa5fff1067feefb8 to your computer and use it in GitHub Desktop.
swapi
// 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