Skip to content

Instantly share code, notes, and snippets.

@jazibsawar
Created January 28, 2019 22:21
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 jazibsawar/d50af99119b8a53093cf624c0b7939b2 to your computer and use it in GitHub Desktop.
Save jazibsawar/d50af99119b8a53093cf624c0b7939b2 to your computer and use it in GitHub Desktop.
gridsome-source-cosmicjs/fetch.js
// gridsome-source-cosmicjs/fetch.js
const axios = require('axios')
const { isObject, startsWith, forEach } = require('lodash')
module.exports = async ({ apiURL, bucketSlug, objectType, apiAccess }) => {
console.time('Fetch Cosmic JS data')
console.log(`Starting to fetch data from Cosmic JS (${objectType})`)
// Define API endpoint.
let apiEndpoint = `${apiURL}/${bucketSlug}/objects?type=${objectType}`
if (apiAccess.hasOwnProperty('read_key') && apiAccess.read_key.length !== 0) {
apiEndpoint = apiEndpoint + `&read_key=${apiAccess.read_key}`
}
// Make API request.
const documents = await axios(apiEndpoint)
// Query all data from endpoint
console.timeEnd('Fetch Cosmic JS data')
// Map and clean data.
if (documents.data.objects) {
return documents.data.objects.map(item => clean(item))
} else {
return []
}
}
/**
* Remove fields starting with `_` symbol.
*
* @param {object} item - Entry needing clean
* @returns {object} output - Object cleaned
*/
const clean = item => {
forEach(item, (value, key) => {
if (startsWith(key, `__`)) {
delete item[key]
} else if (isObject(value)) {
item[key] = clean(value)
}
})
return item
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment