Last active
November 17, 2016 20:24
-
-
Save lricoy/157949519abb043cb09fbf75fbe0af39 to your computer and use it in GitHub Desktop.
Populates an firebase database with the swapi data
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
'use strict'; | |
let firebase = require('firebase-admin'); | |
let axios = require('axios'); | |
let serviceAccount = require('./auth.json'); | |
firebase.initializeApp({ | |
credential: firebase.credential.cert(serviceAccount), | |
databaseURL: 'https://react-quick-start.firebaseio.com' | |
}); | |
let dbRef = firebase.database().ref() | |
function hasUrl (str) { | |
return str.includes('http://') | |
} | |
function getAPIData(url, accumulator) { | |
accumulator = typeof accumulator === 'undefined' | |
? { data: [], url: url } | |
: accumulator | |
return new Promise((resolve, reject) => { | |
axios | |
.get(url) | |
.then(res => res.data) | |
.then(data => { | |
accumulator.data = [].concat( | |
accumulator.data, | |
data.results | |
) | |
if(data.next != null) { | |
resolve(getAPIData(data.next, accumulator)) | |
} | |
else { | |
resolve(accumulator) | |
} | |
}) | |
.catch(err => reject(err)) | |
}) | |
} | |
return axios.get('http://swapi.co/api/') | |
.then(res => res.data) | |
.then(data => { | |
return Object.keys(data) | |
.map(key => data[key]) | |
}) | |
.then(urls => { | |
let promises = urls.map( | |
url => { | |
let promise = getAPIData(url) | |
promise.url = url | |
return promise | |
} | |
) | |
return Promise.all(promises) | |
}) | |
.then(resData => { | |
resData.forEach(urlData => { | |
const stripedUrl = urlData.url | |
.replace('http://swapi.co/api/', '') | |
.replace('/', '') | |
dbRef | |
.child(stripedUrl) | |
.set(urlData.data) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment