UNPKG

gatsby-source-cloudbase-cms

Version:

Gatsby source plugin for building websites using CloudBase CMS as a data source

87 lines (77 loc) 2.32 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _axios = _interopRequireDefault(require("axios")); var _lodash = require("lodash"); module.exports = async (entityDefinition, ctx) => { const { apiURL, apiToken, fetchOptions, queryLimit, reporter } = ctx; const { endpoint, api } = entityDefinition; // Define API endpoint. const apiBase = `${apiURL}/${endpoint}`; const requestOptions = { method: 'GET', url: apiBase, // Place global params first, so that they can be overriden by api.qs params: { limit: queryLimit, ...(api === null || api === void 0 ? void 0 : api.qs) }, headers: addAuthorizationHeader({}, apiToken), ...fetchOptions }; reporter.info(`Starting to fetch data from CloudBase - ${apiBase} with params ${JSON.stringify(requestOptions.params)}`); try { const { data } = await (0, _axios.default)(requestOptions); return (0, _lodash.castArray)(data.data).map(clean); } catch (error) { reporter.panic(`Failed to fetch data from CloudBase`, error); } }; /** * Remove fields starting with `_` symbol. * * @param {object} item - Entry needing clean * @returns {object} output - Object cleaned */ const clean = item => { (0, _lodash.forEach)(item, (value, key) => { if (key === `__v`) { // Remove mongo's __v delete item[key]; } else if (key === `_id`) { // Rename "_id" key to "id". delete item[key]; item.id = value; } else if (key === `_createTime`) { // Rename "_createTime" key to "createdAt". delete item[key]; item.createdAt = value; } else if (key === `_updateTime`) { // Rename "_updateTime" key to "updatedAt". delete item[key]; item.updatedAt = value; } else if ((0, _lodash.startsWith)(key, '__')) { // Gatsby reserves double-underscore prefixes – replace prefix with "cloudBase" delete item[key]; item[`cloudbase_${key.slice(2)}`] = value; } else if ((0, _lodash.isObject)(value)) { item[key] = clean(value); } }); return item; }; const addAuthorizationHeader = (options, token) => { if (token) { (0, _lodash.set)(options, 'Authorization', `Bearer ${token}`); } return options; };