@servicenow/library-enhanced-element
Version:
Base element for Now Design System components
89 lines (81 loc) • 1.87 kB
JavaScript
import get from 'lodash/get';
const castJSON = (properties, prop) => {
if (typeof properties[prop] !== 'string') {
return properties;
}
let value;
try {
value = JSON.parse(properties[prop]);
} catch (e) {
// eslint-disable-next-line no-console
console.error(`The attribute ${prop} is not valid JSON:`, e);
value = {};
}
return {
...properties,
[prop]: value
};
};
const castJSONorString = (properties, prop) => {
if (typeof properties[prop] !== 'string') {
return properties;
}
let value;
try {
value = JSON.parse(properties[prop]);
return {
...properties,
[prop]: value
};
} catch (e) {
return properties;
}
};
const castNumber = (properties, prop) => {
if (typeof properties[prop] !== 'string') {
return properties;
}
if (isNaN(properties[prop])) {
// eslint-disable-next-line no-console
console.error(`The attribute ${prop} is not a number.`);
return properties;
}
return {
...properties,
[prop]: Number(properties[prop])
};
};
const castFunctions = {
array: castJSON,
object: castJSON,
number: castNumber,
objectOrString: castJSONorString
};
export const extendWithCast = (baseConfig) => {
const baseTransformProps = get(
baseConfig,
['renderer', 'transformProps'],
(state) => state
);
const properties = baseConfig.properties || {};
const transforms = Object.keys(properties).reduce((acc, key) => {
if (properties[key].hasOwnProperty('cast')) {
const transform = castFunctions[properties[key].cast];
acc = [...acc, (properties) => transform(properties, key)];
}
return acc;
}, []);
return {
...baseConfig,
renderer: {
...baseConfig.renderer,
transformProps: (state) => {
const properties = transforms.reduce(
(acc, fn) => fn(acc),
state.properties
);
return baseTransformProps({...state, properties: {...properties}});
}
}
};
};