2022-01-21 07:04:44 +13:00
|
|
|
const { FieldTypes, FormulaTypes } = require("../../constants")
|
2021-09-03 05:33:41 +12:00
|
|
|
const { processStringSync } = require("@budibase/string-templates")
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Looks through the rows provided and finds formulas - which it then processes.
|
|
|
|
*/
|
2022-01-22 05:24:24 +13:00
|
|
|
exports.processFormulas = (
|
|
|
|
table,
|
|
|
|
rows,
|
|
|
|
{ dynamic, contextRows } = { dynamic: true }
|
|
|
|
) => {
|
2021-09-03 05:33:41 +12:00
|
|
|
const single = !Array.isArray(rows)
|
|
|
|
if (single) {
|
|
|
|
rows = [rows]
|
2022-01-22 05:24:24 +13:00
|
|
|
contextRows = contextRows ? [contextRows] : contextRows
|
2021-09-03 05:33:41 +12:00
|
|
|
}
|
|
|
|
for (let [column, schema] of Object.entries(table.schema)) {
|
2022-01-21 07:04:44 +13:00
|
|
|
const isStatic = schema.formulaType === FormulaTypes.STATIC
|
|
|
|
if (
|
|
|
|
schema.type !== FieldTypes.FORMULA ||
|
|
|
|
(dynamic && isStatic) ||
|
|
|
|
(!dynamic && !isStatic)
|
|
|
|
) {
|
2021-09-03 05:33:41 +12:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
// iterate through rows and process formula
|
2022-01-22 05:24:24 +13:00
|
|
|
for (let i = 0; i < rows.length; i++) {
|
|
|
|
let row = rows[i]
|
|
|
|
let context = contextRows ? contextRows[i] : row
|
|
|
|
rows[i] = {
|
|
|
|
...row,
|
|
|
|
[column]: processStringSync(schema.formula, context),
|
|
|
|
}
|
|
|
|
}
|
2021-09-03 05:33:41 +12:00
|
|
|
}
|
|
|
|
return single ? rows[0] : rows
|
|
|
|
}
|