-
-
Save jazibsawar/d50af99119b8a53093cf624c0b7939b2 to your computer and use it in GitHub Desktop.
gridsome-source-cosmicjs/fetch.js
This file contains 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
// 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