1
0
Fork 0
mirror of synced 2024-09-12 15:37:31 +12:00
budibase/packages/string-templates/src/utilities.js
Andrew Kingston b402254b2c Lint
2021-05-14 15:41:58 +01:00

57 lines
1.5 KiB
JavaScript

const _ = require("lodash")
const ALPHA_NUMERIC_REGEX = /^[A-Za-z0-9]+$/g
module.exports.FIND_HBS_REGEX = /{{([^{].*?)}}/g
module.exports.isAlphaNumeric = char => {
return char.match(ALPHA_NUMERIC_REGEX)
}
module.exports.swapStrings = (string, start, length, swap) => {
return string.slice(0, start) + swap + string.slice(start + length)
}
// removes null and undefined
module.exports.removeNull = obj => {
obj = _(obj).omitBy(_.isUndefined).omitBy(_.isNull).value()
for (let [key, value] of Object.entries(obj)) {
// only objects
if (typeof value === "object" && !Array.isArray(value)) {
obj[key] = module.exports.removeNull(value)
}
}
return obj
}
module.exports.updateContext = obj => {
if (obj.now == null) {
obj.now = new Date().toISOString()
}
function recurse(obj) {
for (let key of Object.keys(obj)) {
if (!obj[key]) {
continue
}
if (obj[key] instanceof Date) {
obj[key] = obj[key].toISOString()
} else if (typeof obj[key] === "object") {
obj[key] = recurse(obj[key])
}
}
return obj
}
return recurse(obj)
}
module.exports.removeHandlebarsStatements = string => {
let regexp = new RegExp(exports.FIND_HBS_REGEX)
let matches = string.match(regexp)
if (matches == null) {
return string
}
for (let match of matches) {
const idx = string.indexOf(match)
string = exports.swapStrings(string, idx, match.length, "Invalid Binding")
}
return string
}