F OpenNebula/one#5422: Add doc to client/utils

This commit is contained in:
Sergio Betanzos committed 2021-07-12 12:54:04 +02:00
1 parent 6899ba4c54
commit 9cc5c1d702
9 files changed
+288 -46

No files matched your search

@@ -13,17 +13,22 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/** @enum {string} Mode */
const MODE = {
development: 'development',
production: 'production'
}
/** @returns {boolean} `true` if is load in the server */
const isBackend = () => typeof window === 'undefined'
/** @returns {boolean} `true` if production mode enabled */
const isProduction = () => process.env.NODE_ENV === 'production'
/** @returns {boolean} `true` if development mode enabled */
const isDevelopment = () => process.env.NODE_ENV === 'development'
/** @returns {MODE} Mode enabled in NODE_ENV */
export default MODE[process.env.NODE_ENV]
export { isProduction, isDevelopment, isBackend }
+110 -13
View File
@@ -15,25 +15,52 @@
* ------------------------------------------------------------------------- */
import DOMPurify from 'dompurify'
/**
* Simulate a delay in a function.
*
* @param {number} ms - Delay in milliseconds
* @returns {Promise} Promise resolved with a delay
*/
export const fakeDelay = ms => new Promise(resolve => setTimeout(resolve, ms))
/**
* Determines if url is external.
*
* @param {string} url - URL
* @returns {boolean} `true` if url is external
*/
export const isExternalURL = url => RegExp(/^(http|https):/g).test(url)
export const generateKey = () => new Date().getTime() + Math.random()
/**
* Generates a random key.
*
* @returns {string} Random key
*/
export const generateKey = () =>
String(new Date().getTime() + Math.random()).replace('.', '')
export function sanitize (strings, ...values) {
const dirty = strings.reduce((prev, next, i) =>
/**
* Sanitizes HTML and prevents XSS attacks.
*
* @param {string} text - Text
* @param {...string} values - Rest of text
* @returns {string} Clean and secure string
*/
export function sanitize (text, ...values) {
const dirty = text.reduce((prev, next, i) =>
`${prev}${next}${values[i] || ''}`, '')
return DOMPurify.sanitize(dirty)
}
/**
* Converts a long string of units into a readable format e.g KB, MB, GB, TB, YB
* Converts a long string of units into a readable format e.g KB, MB, GB, TB, YB.
*
* @param {Int} value The quantity of units.
* @param {String} unit The unit of value.
* @param {Int} fractionDigits — Number of digits after the decimal point. Must be in the range 0 - 20, inclusive
* @param {number} value - The quantity of units.
* @param {string} unit - The unit of value.
* @param {number} fractionDigits
* - Number of digits after the decimal point. Must be in the range 0 - 20, inclusive
* @returns {string} Returns an string displaying sizes for humans.
*/
export const prettyBytes = (value, unit = 'KB', fractionDigits = 0) => {
const UNITS = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
@@ -50,21 +77,54 @@ export const prettyBytes = (value, unit = 'KB', fractionDigits = 0) => {
return `${value.toFixed(fractionDigits)} ${UNITS[idxUnit]}`
}
/**
* Add opacity value to a HEX color.
*
* @param {string} color - HEX color
* @param {number} opacity - Opacity range: 0 to 1
* @returns {string} The color with opacity
*/
export const addOpacityToColor = (color, opacity) => {
const opacityHex = Math.round(opacity * 255).toString(16)
return `${color}${opacityHex}`
}
/**
* Capitalize the first letter of a string.
*
* @param {string} word - Word
* @returns {string} The word capitalized
*/
export const capitalize = ([firstLetter, ...restOfWord]) =>
firstLetter.toUpperCase() + restOfWord.join('')
/**
* Converts an string to camel case.
*
* @param {string} s - String
* @example permissions_panel => permissionsPanel
* @returns {string} String with camel case format
*/
export const stringToCamelCase = s => s.replace(
/([-_\s][a-z])/ig,
$1 => $1.toUpperCase().replace(/[-_\s]/g, '')
)
/**
* Converts an string in camel case to camel space.
*
* @param {string} s - String
* @example permissionsPanel => 'permissions panel'
* @returns {string} String with camel space format
*/
export const stringToCamelSpace = s => s.replace(/([a-z])([A-Z])/g, '$1 $2')
/**
* Returns the validation by name from the form schema.
*
* @param {Array} fields - Field schemas
* @returns {object} List of validations
*/
export const getValidationFromFields = fields =>
fields.reduce(
(schema, field) => ({
@@ -74,6 +134,13 @@ export const getValidationFromFields = fields =>
{}
)
/**
* Filter an object list by property.
*
* @param {Array} arr - Object list
* @param {string} predicate - Property
* @returns {Array} List filtered by predicate
*/
export const filterBy = (arr, predicate) => {
const callback =
typeof predicate === 'function' ? predicate : output => output[predicate]
@@ -91,6 +158,14 @@ export const filterBy = (arr, predicate) => {
]
}
/**
* Get the value from an object by the path of property.
*
* @param {object} obj - Object
* @param {string} path - Path of property
* @param {*} [defaultValue] - Default value of property
* @returns {*} Value of property
*/
export const get = (obj, path, defaultValue = undefined) => {
const travel = regexp =>
String.prototype.split
@@ -102,6 +177,14 @@ export const get = (obj, path, defaultValue = undefined) => {
return result === undefined || result === obj ? defaultValue : result
}
/**
* Set a value of property in object by his path.
*
* @param {object} obj - Object
* @param {string} path - Path of property
* @param {*} value - New value of property
* @returns {object} Object with the new property
*/
export const set = (obj, path, value) => {
if (Object(obj) !== obj) return obj // When obj is not an object
@@ -124,8 +207,15 @@ export const set = (obj, path, value) => {
return result
}
export const groupBy = (array, key) =>
array.reduce((objectsByKeyValue, obj) => {
/**
* Group a list of objects by a key.
*
* @param {object[]} list - List
* @param {string} key - Property
* @returns {object} Objects group by the property
*/
export const groupBy = (list, key) =>
list.reduce((objectsByKeyValue, obj) => {
const keyValue = get(obj, key)
const newValue = (objectsByKeyValue[keyValue] || []).concat(obj)
@@ -134,14 +224,21 @@ export const groupBy = (array, key) =>
return objectsByKeyValue
}, {})
/**
* Clone an object.
*
* @param {object} obj - Object
* @returns {object} Object cloned
*/
export const cloneObject = obj => JSON.parse(JSON.stringify(obj))
/**
* Check if value is in base64
* Check if value is in base64.
*
* @param {String} stringToValidate String to check
* @param {Boolean} options.exact Only match and exact string
* @returns {Boolean}
* @param {string} stringToValidate - String to check
* @param {object} options - Options
* @param {boolean} options.exact - Only match and exact string
* @returns {boolean} Returns `true` if string is a base64
*/
export const isBase64 = (stringToValidate, options = {}) => {
if (stringToValidate === '') return false
+60 -25
View File
@@ -13,7 +13,17 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
export const isMergeableObject = (val) => {
/**
* @typedef {object} MergeOptions
* @property {Function} arrayMerge - Function to merge two arrays
* @property {boolean} clone - Clone the object
*/
/**
* @param {object|Array} val - Value
* @returns {boolean} Returns `true` if value isn't regex or date object
*/
export const isMergeableObject = val => {
var nonNullObject = val && typeof val === 'object'
return nonNullObject &&
@@ -21,68 +31,93 @@ export const isMergeableObject = (val) => {
Object.prototype.toString.call(val) !== '[object Date]'
}
export const emptyTarget = (val) => {
return Array.isArray(val) ? [] : {}
/**
* @param {object|Array} val - Value
* @returns {object|Array} Empty value
*/
export const emptyTarget = val => Array.isArray(val) ? [] : {}
/**
* @param {Array} value - Value
* @param {MergeOptions} options - Merge options
* @returns {*} Returns the value as clone if required
*/
export const cloneIfNecessary = (value, options) => {
return (options?.clone === true && isMergeableObject(value))
? deepmerge(emptyTarget(value), value, options) : value
}
export const cloneIfNecessary = (value, optionsArgument) => {
var clone = optionsArgument && optionsArgument.clone === true
return (clone && isMergeableObject(value))
? deepmerge(emptyTarget(value), value, optionsArgument) : value
}
export const defaultArrayMerge = (target, source, optionsArgument) => {
/**
* @param {Array} target - Target
* @param {Array} source - Source
* @param {MergeOptions} options - Merge options
* @returns {Array} Two arrays merged
*/
export const defaultArrayMerge = (target, source, options) => {
var destination = target.slice()
source.forEach(function (e, i) {
if (typeof destination[i] === 'undefined') {
destination[i] = cloneIfNecessary(e, optionsArgument)
destination[i] = cloneIfNecessary(e, options)
} else if (isMergeableObject(e)) {
destination[i] = deepmerge(target[i], e, optionsArgument)
destination[i] = deepmerge(target[i], e, options)
} else if (target.indexOf(e) === -1) {
destination.push(cloneIfNecessary(e, optionsArgument))
destination.push(cloneIfNecessary(e, options))
}
})
return destination
}
export const mergeObject = (target, source, optionsArgument) => {
/**
* @param {object} target - Target
* @param {object} source - Source
* @param {MergeOptions} options - Merge options
* @returns {object} Two object merged
*/
export const mergeObject = (target, source, options) => {
var destination = {}
if (isMergeableObject(target)) {
Object.keys(target).forEach(function (key) {
destination[key] = cloneIfNecessary(target[key], optionsArgument)
destination[key] = cloneIfNecessary(target[key], options)
})
}
Object.keys(source).forEach(function (key) {
if (!isMergeableObject(source[key]) || !target[key]) {
destination[key] = cloneIfNecessary(source[key], optionsArgument)
destination[key] = cloneIfNecessary(source[key], options)
} else {
destination[key] = deepmerge(target[key], source[key], optionsArgument)
destination[key] = deepmerge(target[key], source[key], options)
}
})
return destination
}
export const deepmerge = (target, source, optionsArgument) => {
/**
* Merges the enumerable properties of two or more objects deeply.
*
* @param {object} target - Target
* @param {object} source - Source
* @param {MergeOptions} options - Merge options
* @returns {object} Two object merged
*/
export const deepmerge = (target, source, options = {}) => {
var array = Array.isArray(source)
var options = optionsArgument || { arrayMerge: defaultArrayMerge }
var arrayMerge = options.arrayMerge || defaultArrayMerge
const { arrayMerge = defaultArrayMerge } = options
if (array) {
return Array.isArray(target)
? arrayMerge(target, source, optionsArgument)
: cloneIfNecessary(source, optionsArgument)
? arrayMerge(target, source, options)
: cloneIfNecessary(source, options)
} else {
return mergeObject(target, source, optionsArgument)
return mergeObject(target, source, options)
}
}
deepmerge.all = function deepmergeAll (array, optionsArgument) {
deepmerge.all = function deepmergeAll (array, options) {
if (!Array.isArray(array) || array.length < 2) {
throw new Error('first argument should be an array with at least two elements')
}
// we are sure there are at least 2 values, so it is safe to have no initial value
return array.reduce(function (prev, next) {
return deepmerge(prev, next, optionsArgument)
return deepmerge(prev, next, options)
})
}
@@ -50,9 +50,7 @@ const parseCluster = tiers => {
const NUM_REG = /(\d+)/g
const clusters = tiers?.map(({ vm_template_contents: content = '' }) => {
const { sched_requirements: schedRequirements } = templateToObject(
content
)
const { sched_requirements: schedRequirements } = templateToObject(content)
return schedRequirements?.match(NUM_REG)?.join()
})
@@ -135,6 +133,12 @@ const parseTiers = (roles, networking) =>
return [...res, { ...tier, parents }]
}, [])
/**
* Parses service application data to form structure.
*
* @param {object} data - OpenNebula service
* @returns {object} Form data
*/
const mapApplicationToForm = data => {
const {
NAME,
@@ -29,6 +29,15 @@ const mapNetworkToUserInput = network => {
return `${mandatoryValue}|network|${descriptionValue}| |${type}:${idVnetValue}${extraValue}`
}
/**
* Map tiers defined in the form and transforms
* to OpenNebula service template role.
*
* @param {Array} tiers - Tiers defined in the form
* @param {Array} networking - List of networks
* @param {string|number} cluster - Cluster id
* @returns {Array} Roles
*/
export const mapTiersToRoles = (tiers, networking, cluster) =>
tiers?.map(data => {
const { template, networks, parents, policies, position, tier } = data
@@ -74,13 +83,19 @@ export const mapTiersToRoles = (tiers, networking, cluster) =>
}
})
const mapFormToApplication = data => {
/**
* Formats form data to create or update an OpenNebula service template.
*
* @param {object} formData - Form data
* @returns {object} Formatted data ready to create or update the template.
*/
const mapFormToApplication = formData => {
const {
[APPLICATION_ID]: application,
[NETWORKING_ID]: networking,
[CLUSTER_ID]: cluster,
[TIERS_ID]: tiers
} = data
} = formData
const { shutdown_action: action, ...information } = application
@@ -20,6 +20,15 @@ import { STEP_ID as CLUSTER_ID } from 'client/containers/ApplicationsTemplates/F
import { mapUserInputs, deepmerge } from 'client/utils'
/**
* Map tiers defined in the form and transforms
* to OpenNebula service role.
*
* @param {Array} tiers - Tiers defined in the form
* @param {Array} networking - List of networks
* @param {string|number} cluster - Cluster id
* @returns {Array} Roles
*/
export const mapTiersToRoles = (tiers, networking, cluster) =>
tiers?.map(data => {
const { template, parents, networks, user_inputs_values = {}, tier } = data
@@ -48,7 +57,14 @@ export const mapTiersToRoles = (tiers, networking, cluster) =>
}
})
const mapFormparseFormToDeployApplication = (formData, template) => {
/**
* Formats form data to deploy OpenNebula service.
*
* @param {object} formData - Form data
* @param {object} template - Current template
* @returns {object} Formatted data ready to deploy.
*/
const parseFormToDeployApplication = (formData, template) => {
const {
[BASIC_ID]: application,
[NETWORKING_ID]: networking,
@@ -66,4 +82,4 @@ const mapFormparseFormToDeployApplication = (formData, template) => {
}
}
export default mapFormparseFormToDeployApplication
export default parseFormToDeployApplication
@@ -20,6 +20,12 @@ const sanitizeKey = key => key?.trim().toLowerCase()
const sanitizeValue = value => value?.trim().replaceAll(/[\\"]/g, '')
/**
* Parses OpenNebula resource template to json.
*
* @param {string} template - OpenNebula resource template
* @returns {object} JSON of template
*/
const parseTemplateToObject = template => {
const stringWithoutNewLines = JSON.stringify(template).replaceAll(/\\n/g, '')
+44 -1
View File
@@ -29,6 +29,39 @@ const getValuesFromArray = (options, separator = ';') => options?.split(separato
const getOptionsFromList = (options, separator = ',') =>
options?.split(separator).map(value => ({ text: value, value }))
/**
* @typedef {(
* 'text'|
* 'text64'|
* 'password'|
* 'number'|
* 'number-float'|
* 'range'|
* 'range-float'|
* 'boolean'|
* 'list'|
* 'array'|
* 'list-multiple'
* )} TypeInput - OpenNebula types for user inputs
*/
/**
* Get input schema for the user input defined in OpenNebula resource.
*
* @param {object} userInput - User input from OpenNebula document
* @param {boolean} userInput.mandatory - If `true`, the input will be required
* @param {string} userInput.name - Name of input
* @param {userInput} userInput.type - Input type
* @param {string} [userInput.options] - Options available for the input
* @param {number|string|string[]} [userInput.defaultValue] - Default value for the input
* @returns {{
* type: INPUT_TYPES,
* htmlType: string,
* multiple: boolean,
* validation: yup.AnyObjectSchema,
* fieldProps: object
* }} Schema properties
*/
export const schemaUserInput = ({ mandatory, name, type, options, defaultValue }) => {
switch (type) {
case 'text':
@@ -134,7 +167,17 @@ const parseUserInputValue = value => {
} else return value
}
export const mapUserInputs = userInputs =>
/**
* Parse JS values to OpenNebula values.
*
* @param {object} userInputs - List of user inputs
* @example <caption>Example of parsed</caption>
* // { user_ssh: true } => { user_ssh: 'YES' }
* // { groups: [1, 2, 3] } => { groups: '1,2,3' }
* @returns {object}
* - Returns same object with values can be operated by OpenNebula
*/
export const mapUserInputs = (userInputs = {}) =>
Object.entries(userInputs)?.reduce((res, [key, value]) => ({
...res, [key]: parseUserInputValue(value)
}), {})
+21
View File
@@ -15,6 +15,16 @@
* ------------------------------------------------------------------------- */
import root from 'window-or-global'
/**
* Save an item in the browser storage.
*
* @param {string} name
* - Name of item in the storage
* @param {string} data
* - Data will be saved into storage
* @param {boolean} keepData
* - If `true`, save the data in local storage, instead of session storage
*/
export const storage = (name = '', data = '', keepData = false) => {
if (name && data) {
keepData
@@ -23,6 +33,11 @@ export const storage = (name = '', data = '', keepData = false) => {
}
}
/**
* Remove group of items from the browser storage.
*
* @param {string[]} items - List of item names
*/
export const removeStoreData = (items = []) => {
const itemsToRemove = !Array.isArray(items) ? [items] : items
@@ -32,6 +47,12 @@ export const removeStoreData = (items = []) => {
})
}
/**
* Looking for an item in the browser storage.
*
* @param {string} name - Name of item
* @returns {object|string} Returns the item if found it
*/
export const findStorageData = (name = '') => {
if (name && root?.localStorage?.getItem(name)) {
return root.localStorage.getItem(name)