Skip to content

Instantly share code, notes, and snippets.

@igorkosta
Last active March 18, 2021 09:36
Show Gist options
  • Save igorkosta/48f0fd623348f0741a09184942ede741 to your computer and use it in GitHub Desktop.
Save igorkosta/48f0fd623348f0741a09184942ede741 to your computer and use it in GitHub Desktop.
Get all characters with respective movie titles they appeared in
const axios = require('axios');
const PEOPLE_URL = 'https://swapi.dev/api/people/';
const FILMS_URL = 'https://swapi.dev/api/films/';
let people = [];
async function fetchPeople(url = PEOPLE_URL) {
try {
var { data } = await axios.get(url);
people = people.concat(data.results);
if (data.next) {
await fetchPeople(data.next)
}
return people;
} catch (error) {
throw new Error(`Error fetching swapi people: ${error}`);
}
}
async function getMovieTitles(url = FILMS_URL) {
let films = {};
try {
const { data: { results: movies} } = await axios.get(url);
for (let { url, title } of movies) {
films[url] = title
};
return films;
} catch (error) {
throw new Error(`Error fetching movie titles: ${error}`);
}
}
async function charactersWithMovies() {
try {
let people = await fetchPeople();
let movies = await getMovieTitles();
const result = people.map((person) => {
const titles = person.films.map((film) => movies[film]);
return {...person, 'movies': titles };
});
console.log(JSON.stringify(result, null, 2));
return result;
} catch (error) {
throw new Error(`Error adding movie titles to characters: ${error}`);
}
};
(async() => {
console.log('------------- START ---------------')
await charactersWithMovies();
console.log('------------- STOP ---------------')
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment