budibase/packages/core/src/templateApi/canDeleteIndex.js

55 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-03-27 17:58:32 +01:00
import {
findRoot,
2020-03-24 11:56:48 +01:00
getFlattenedHierarchy,
fieldReversesReferenceToIndex,
2020-03-27 17:58:32 +01:00
isRecord,
2020-03-24 11:56:48 +01:00
} from "./hierarchy"
import { $ } from "../common"
import { map, filter, reduce } from "lodash/fp"
export const canDeleteIndex = indexNode => {
2020-03-27 17:58:32 +01:00
const flatHierarchy = $(indexNode, [findRoot, getFlattenedHierarchy])
2020-03-24 11:56:48 +01:00
2020-03-27 17:58:32 +01:00
const reverseIndexes = $(flatHierarchy, [
2020-03-24 11:56:48 +01:00
filter(isRecord),
reduce((obj, r) => {
for (let field of r.fields) {
if (fieldReversesReferenceToIndex(indexNode)(field)) {
2020-03-27 17:58:32 +01:00
obj.push({ ...field, record: r })
2020-03-24 11:56:48 +01:00
}
}
return obj
2020-03-27 17:58:32 +01:00
}, []),
map(
f =>
`field "${f.name}" on record "${f.record.name}" uses this index as a reference`
),
2020-03-24 11:56:48 +01:00
])
2020-03-27 17:58:32 +01:00
const lookupIndexes = $(flatHierarchy, [
2020-03-24 11:56:48 +01:00
filter(isRecord),
reduce((obj, r) => {
for (let field of r.fields) {
2020-03-27 17:58:32 +01:00
if (
field.type === "reference" &&
field.typeOptions.indexNodeKey === indexNode.nodeKey()
) {
obj.push({ ...field, record: r })
2020-03-24 11:56:48 +01:00
}
}
return obj
2020-03-27 17:58:32 +01:00
}, []),
map(
f =>
`field "${f.name}" on record "${f.record.name}" uses this index as a lookup`
),
2020-03-24 11:56:48 +01:00
])
2020-03-27 17:58:32 +01:00
const errors = [...reverseIndexes, ...lookupIndexes]
2020-03-24 11:56:48 +01:00
return {
canDelete: errors.length === 0,
2020-03-27 17:58:32 +01:00
errors,
2020-03-24 11:56:48 +01:00
}
2020-03-27 17:58:32 +01:00
}