2022-02-04 19:00:08 +01:00
|
|
|
import { Variable } from 'models'
|
2022-01-14 07:49:24 +01:00
|
|
|
import { isDefined } from 'utils'
|
|
|
|
|
|
|
|
const safeEval = eval
|
|
|
|
|
|
|
|
export const stringContainsVariable = (str: string): boolean =>
|
|
|
|
/\{\{(.*?)\}\}/g.test(str)
|
|
|
|
|
2022-02-07 18:06:37 +01:00
|
|
|
export const parseVariables =
|
|
|
|
(variables: Variable[]) =>
|
|
|
|
(text?: string): string => {
|
|
|
|
if (!text || text === '') return ''
|
|
|
|
return text.replace(/\{\{(.*?)\}\}/g, (_, fullVariableString) => {
|
|
|
|
const matchedVarName = fullVariableString.replace(/{{|}}/g, '')
|
|
|
|
return (
|
|
|
|
variables.find((v) => {
|
|
|
|
return matchedVarName === v.name && isDefined(v.value)
|
|
|
|
})?.value ?? ''
|
|
|
|
)
|
|
|
|
})
|
|
|
|
}
|
2022-01-14 07:49:24 +01:00
|
|
|
|
|
|
|
export const evaluateExpression = (str: string) => {
|
|
|
|
try {
|
2022-03-02 18:58:10 +01:00
|
|
|
const evaluatedResult = safeEval(str)
|
|
|
|
return evaluatedResult.toString()
|
2022-01-14 07:49:24 +01:00
|
|
|
} catch (err) {
|
2022-03-02 18:58:10 +01:00
|
|
|
return str
|
2022-01-14 07:49:24 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-19 14:25:15 +01:00
|
|
|
export const parseVariablesInObject = (
|
|
|
|
object: { [key: string]: string | number },
|
2022-02-04 19:00:08 +01:00
|
|
|
variables: Variable[]
|
2022-01-19 14:25:15 +01:00
|
|
|
) =>
|
|
|
|
Object.keys(object).reduce((newObj, key) => {
|
|
|
|
const currentValue = object[key]
|
|
|
|
return {
|
|
|
|
...newObj,
|
|
|
|
[key]:
|
|
|
|
typeof currentValue === 'string'
|
2022-02-07 18:06:37 +01:00
|
|
|
? parseVariables(variables)(currentValue)
|
2022-01-19 14:25:15 +01:00
|
|
|
: currentValue,
|
|
|
|
}
|
|
|
|
}, {})
|