DigitalConsumer.FixMyGlass/src/helpers/cms-content-helper.js
2021-12-17 15:49:51 -05:00

100 lines
No EOL
3.1 KiB
JavaScript

import { storeActions } from "@/constants/store-actions.js";
import { widgetNames } from "@/constants/widget-names.js";
import store from "@/store";
export function fetchCmsContentForPage(fmgPage) {
return store
.dispatch(storeActions.GET_PAGE_DATA, { pageName: fmgPage })
.then((response) => {
const pageDataFromCms = {};
response.data.Result.forEach((widget) => {
let widgetWithReplacements = findAndReplaceGlobalStateValues(widget.Model, widget.Type);
if (Object.values(widgetNames).includes(widgetWithReplacements.Type)) {
// If we already have this widget, push it on the collection
if (widgetWithReplacements.Type in pageDataFromCms) {
pageDataFromCms[widgetWithReplacements.Type].push(widgetWithReplacements.Model);
return;
}
pageDataFromCms[widgetWithReplacements.Type] = [widgetWithReplacements.Model];
}
});
return pageDataFromCms;
});
}
// Function to convert a string, into a matching global state item.
function mapStringToState(str) {
// Pull all matches out of the string.
const regexExp = new RegExp('{(.*?):(.*?)}', 'g');
const matches = [...str.matchAll(regexExp)];
// Our final string value that will be built from the matches.
let stringBuilder = '';
for (const match of matches) {
// Reset store state for each match.
let storeState = store.state;
for (const s of match[2].split('.')) {
if (storeState[s] != undefined) {
storeState = storeState[s];
} else {
return false;
}
}
// Concatenate the string.
stringBuilder = `${stringBuilder} ${storeState}`;
}
return stringBuilder.trimStart();
}
// Parent function for processWidgetItemForReplacement. This will loop through the parent
// object and pass any objects that need additional processing to the processWidgetItemForReplacement function.
function findAndReplaceGlobalStateValues(widgetModel, widgetType) {
const objWithReplacements = {
Type: widgetType,
Model: {}
};
Object.keys(widgetModel).forEach(key => {
let modelWithReplacements = processWidgetItemForReplacement(widgetModel, key);
objWithReplacements.Model[key] = modelWithReplacements;
});
return objWithReplacements;
}
// This function will process the widget item and replace any global state variables with their values.
// This is a recursive function, it will call itself until it runs out of items to iterate on given the object.
function processWidgetItemForReplacement(widgetModel, key) {
// If we have a string, and it needs to be replaced.
if (typeof widgetModel[key] === 'string') {
if (widgetModel[key].includes('{globalState:')) {
widgetModel[key] = mapStringToState(widgetModel[key]);
}
return widgetModel[key];
}
// If we have an object. array, etc
if (typeof widgetModel[key] === 'object' && Object.keys(widgetModel[key]).length) {
Object.keys(widgetModel[key]).forEach(item => {
processWidgetItemForReplacement(widgetModel[key], item);
});
return widgetModel[key];
}
return widgetModel[key];
}