Skip to content

Instantly share code, notes, and snippets.

@Jinksi
Last active July 21, 2020 13:19
Show Gist options
  • Save Jinksi/446bf9c973fce7b943bd35cdc3142528 to your computer and use it in GitHub Desktop.
Save Jinksi/446bf9c973fce7b943bd35cdc3142528 to your computer and use it in GitHub Desktop.
Fetch firebase REST API data and save to .json file
const fetch = require('node-fetch')
const fs = require('fs')
const config = {
endpoint: 'https://FIREBASE_PROJECT.firebaseio.com/',
pathsToFetch: [
// database nodes
'pages',
'posts'
],
dataFileName: './src/data.json'
}
const writeFile = ({filename, data}) => {
console.log(`Writing file ${filename}`)
fs.writeFileSync(filename, JSON.stringify(data, null, 2))
console.log(`Writing file ${filename} Complete ✅`)
}
const reduceArrayToObject = (dataObj, data) => ({
...dataObj,
...data
})
const fetchData = () => {
if (!config.endpoint) return console.error(`Please add 'REACT_APP_FIREBASE_ENDPOINT' to .env`)
const fetchPromises = config.pathsToFetch.map(
path => {
console.log(`Fetching ${config.endpoint + path}`)
return fetch(config.endpoint + path + '.json')
.then(response => response.json())
.then(data => {
console.log(`Fetching ${config.endpoint + path} Complete ✅`)
return data
})
.then(data => ({ [path]: data }))
}
)
Promise.all(fetchPromises)
.then(dataArr => dataArr.reduce(reduceArrayToObject, {}))
.then(data => writeFile({
data,
filename: config.dataFileName
}))
.catch(console.error)
}
fetchData()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment