0

I'm using Domain-Driven Design and CQRS on my project and I have a self-referencing aggregate root to model a hierarchical structure:

Category
  CategoryId $id
  CategoryName $name
  ?CategoryId $parentId
  CategoryPosition $position

Now I want to create a feature to sort the category tree. I receive the following structure on an API controller:

[
  {
    "id": "ffb03f1d-dade-4f45-80d5-6e28fea17e70",
    "children": [
      {
        "id": "bdb82eb6-59ea-4645-ae70-d03b5e01c4b6",
        "children": [
          {
            "id": "0ad9c916-eb64-4b0a-b2d0-6864b81b304f",
            "children": []
          }
        ]
      },
      {
        "id": "afa58caf-a0b4-4787-b784-ed3344af2b2b",
        "children": [
          {
            "id": "6f334ab9-47b3-4f7b-8f87-f9c36db8afe5",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "id": "7d3b6110-c282-42b3-b649-efc9394fa5f0",
    "children": []
  }
]

Currently I'm recursively traversing the new tree in infrastructure handling a MoveCategory command to change parentId and position for each category in the tree.

I cannot do it with a single command, because each command should modify a single Category.
Also I'm checking that tree depth is not over 4 levels, which is a domain rule.

The question is, how can I traverse the new tree and do changes on domain layer?

David
  • 503
  • 3
  • 7
  • 18
  • What do you mean exactly by "sort the tree"? – Francesc Castells Sep 22 '22 at 14:33
  • @FrancescCastells I've added an example to the question. I mean changing categories positions and parents – David Sep 22 '22 at 18:31
  • 1
    How large is the tree? having each category as a separate aggregate doesn't help you much here. Can you make the whole tree a single aggregate? Then the problem gets simplified a lot and the aggregate can take care of all the business rules (depth) and logic (rearranging) in a single operation. – Francesc Castells Sep 22 '22 at 18:37
  • @FrancescCastells You mean creating a `CategoryTree` aggregate root with `Category[]` as sub-entities, don't you? I expect 50-100 categories in the tree. It's a good option, I wanted to avoid it because it adds a bit of complexity to other commands (i.e. rename category) but I think it will be the best way. Thank you. – David Sep 23 '22 at 07:05
  • Yeah, that's what I meant. For things like rename, you have multiple options. One is that Category is an aggregate too, to handle renames and stuff, and CategoryTree only has a tree of CategoryIds. The other is to make the implementation of CategoryTree ready for this type of operation. Have a (flat) dictionary of Categories, so you can easily locate and operate with them and also a tree of Ids. Also, you can drop the Position property if you order the collection of Child nodes in the tree. – Francesc Castells Sep 23 '22 at 08:44

0 Answers0