gatsby-source-payload-cms
Version:
Source data from Payload CMS
166 lines (165 loc) • 6.99 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeCollections = exports.normalizeGlobals = exports.payloadImageUrl = exports.payloadImage = exports.documentRelationships = exports.gatsbyNodeTypeName = exports.fetchDataMessage = exports.fetchGraphQL = void 0;
const dot_object_1 = __importDefault(require("dot-object"));
const node_fetch_1 = __importDefault(require("node-fetch"));
const lodash_1 = require("lodash");
const pluralize_1 = require("pluralize");
const capitalizeFirstLetter = (string) => string.charAt(0).toUpperCase() + string.slice(1);
const toWords = (inputString, joinWords = false) => {
const notNullString = inputString || '';
const trimmedString = notNullString.trim();
const arrayOfStrings = trimmedString.split(/[\s-]/);
const splitStringsArray = [];
arrayOfStrings.forEach((tempString) => {
if (tempString !== '') {
const splitWords = tempString.split(/(?=[A-Z])/).join(' ');
splitStringsArray.push(capitalizeFirstLetter(splitWords));
}
});
return joinWords ? splitStringsArray.join('').replace(/\s/g, '') : splitStringsArray.join(' ');
};
const formatNames = (slug) => {
const words = toWords(slug, true);
return (0, pluralize_1.isPlural)(slug)
? {
plural: words,
singular: (0, pluralize_1.singular)(words),
}
: {
plural: (0, pluralize_1.plural)(words),
singular: words,
};
};
const headers = {
"Content-Type": `application/json`,
};
/**
* Fetch utility for requests to the example api.
* You can use a GraphQL client module instead if you prefer a more full-featured experience.
* @see https://graphql.org/code/#javascript-client
*/
function fetchGraphQL(endpoint, query) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield (0, node_fetch_1.default)(endpoint, {
method: `POST`,
headers,
body: JSON.stringify({
query,
}),
});
return (yield response.json());
});
}
exports.fetchGraphQL = fetchGraphQL;
const fetchDataMessage = (url, serializedParams) => {
const message = [`Starting to fetch data from Payload - ${url}`];
if (!(0, lodash_1.isEmpty)(serializedParams)) {
message.push(`with ${serializedParams}`);
}
return message.join(` `);
};
exports.fetchDataMessage = fetchDataMessage;
const gatsbyNodeTypeName = ({ payloadSlug, prefix = `Payload` }) => {
const fromSlug = formatNames(payloadSlug);
const singularName = fromSlug.singular;
return `${prefix}${singularName}`;
};
exports.gatsbyNodeTypeName = gatsbyNodeTypeName;
/**
* Get doc relationships
*
* From an API response, return dot notation key value pairs of relationship ids only.
*
* Note that this only works if the relationship is expanded.
* i.e. it includes an `id` field. Consider adding support
* for non-expanded relationships. e.g.
* ``"hereForYou.image": "64877d207ac104cf4d385657"`.
*
* The document id is excluded (desirable) because it doesn't
* end with `.id`. e.g. `"id": "64877d207ac104cf4d385657"`.
*/
const documentRelationships = (doc, prefix) => {
const document = prefix
? {
[prefix]: doc,
}
: doc;
const dotNotationDoc = dot_object_1.default.dot(document);
return (0, lodash_1.omitBy)(dotNotationDoc, (_value, key) => !key.endsWith(`.id`));
};
exports.documentRelationships = documentRelationships;
const removeTrailingSlash = (str) => str.replace(/\/$/, ``);
const payloadImage = (apiResponse, size) => {
let image = size ? (0, lodash_1.get)(apiResponse, `sizes.${size}`, apiResponse) : apiResponse;
// some sizes may not exist (e.g resize operations on images that are too small)
if (!image || !image.url) {
image = apiResponse;
}
return image;
};
exports.payloadImage = payloadImage;
const payloadImageUrl = (apiResponse, size, baseUrl) => {
if (!apiResponse || typeof apiResponse.url === `undefined`) {
return undefined;
}
const url = (0, exports.payloadImage)(apiResponse, size).url;
return url ? `${removeTrailingSlash(baseUrl)}${url}` : undefined;
};
exports.payloadImageUrl = payloadImageUrl;
const normalizeGlobals = (globalTypes, endpoint) => {
if (!globalTypes) {
return [];
}
return globalTypes.map((globalType) => {
return normalizeGlobal(globalType, endpoint);
});
};
exports.normalizeGlobals = normalizeGlobals;
const normalizeCollections = (collectionTypes, endpoint) => {
if (!collectionTypes) {
return [];
}
return collectionTypes.map((collectionType) => normalizeCollection(collectionType, endpoint));
};
exports.normalizeCollections = normalizeCollections;
const normalizeCollection = (collectionType, endpoint) => {
if ((0, lodash_1.isString)(collectionType)) {
return normalizeCollectionString(collectionType, endpoint);
}
return normalizeCollectionObject(collectionType, endpoint);
};
const normalizeCollectionString = (collectionType, endpoint) => ({
endpoint: new URL(`${collectionType}`, endpoint).href,
type: collectionType,
});
const normalizeCollectionObject = (collectionType, endpoint) => {
const urlPath = collectionType.apiPath ? collectionType.apiPath : collectionType.slug;
return Object.assign(Object.assign({ endpoint: new URL(`${urlPath}`, endpoint).href }, collectionType), { type: collectionType.slug });
};
const normalizeGlobal = (globalType, endpoint) => {
if ((0, lodash_1.isString)(globalType)) {
return normalizeGlobalString(globalType, endpoint);
}
return normalizeGlobalObject(globalType, endpoint);
};
const normalizeGlobalString = (globalType, endpoint) => ({
endpoint: new URL(`globals/${globalType}`, endpoint).href,
type: globalType,
});
const normalizeGlobalObject = (globalType, endpoint) => {
const urlPath = globalType.apiPath ? globalType.apiPath : `globals/${globalType.slug}`;
return Object.assign(Object.assign({ endpoint: new URL(urlPath, endpoint).href }, globalType), { type: globalType.slug });
};