change: Clean the tree in the API call, cleaning utilities

tree-clean-utils: `TreeActions.cleanTreeModel` and `TreeActions.cleanItemModel` have been created. They simply fix the structure of their respective models.
/api/tree: /api/tree now always returns a cleaned tree.
This commit is contained in:
tecc 2022-12-18 22:19:52 +01:00
parent 17b344f3eb
commit e3af53caf2
No known key found for this signature in database
GPG Key ID: 400AAD881FCC028B
2 changed files with 48 additions and 1 deletions

View File

@ -143,6 +143,51 @@ export function makeHierarchy(
};
}
export function cleanItemModel(model: Partial<TreeItemModel>): TreeItemModel {
if (!model.id) throw new Error("Missing id on tree model");
const children = model.children ?? [];
return {
...model, // In case
id: model.id,
children,
hasChildren: children.length > 0,
data: model.data,
isExpanded: model.isExpanded ?? false,
};
}
export function cleanTreeModel(model: Partial<TreeModel>): TreeModel {
const items: TreeModel["items"] = {};
if (model.items) {
for (const itemId in model.items) {
const item = model.items[itemId];
if (!item) {
continue;
}
const cleanedItem = cleanItemModel(item);
const children = [];
for (const child of cleanedItem.children) {
if (child && model.items[child]) {
children.push(child);
}
}
items[itemId] = {
...cleanedItem,
children
};
}
}
return {
...model, // In case
rootId: model.rootId ?? ROOT_ID,
items: items
};
}
const TreeActions = {
addItem,
mutateItem,
@ -152,6 +197,8 @@ const TreeActions = {
deleteItem,
flattenTree,
makeHierarchy,
cleanTreeModel,
cleanItemModel
};
export default TreeActions;

View File

@ -7,7 +7,7 @@ export default api()
.use(useAuth)
.use(useStore)
.get(async (req, res) => {
const tree = await req.state.treeStore.get();
const tree = TreeActions.cleanTreeModel(await req.state.treeStore.get());
const style = req.query['style'];
switch (style) {
case 'hierarchy':