From e3af53caf2f8d5ddbaaf6ee0a4d0f0e937b0014f Mon Sep 17 00:00:00 2001 From: tecc Date: Sun, 18 Dec 2022 22:19:52 +0100 Subject: [PATCH] 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. --- libs/shared/tree.ts | 47 +++++++++++++++++++++++++++++++++++++++++++++ pages/api/tree.ts | 2 +- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/libs/shared/tree.ts b/libs/shared/tree.ts index 9a4fcafbe..b4cc1a55d 100644 --- a/libs/shared/tree.ts +++ b/libs/shared/tree.ts @@ -143,6 +143,51 @@ export function makeHierarchy( }; } +export function cleanItemModel(model: Partial): 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 { + 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; diff --git a/pages/api/tree.ts b/pages/api/tree.ts index 4d1a4a23e..f342f383e 100644 --- a/pages/api/tree.ts +++ b/pages/api/tree.ts @@ -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':