diff --git a/lib/api/v3/custom_fields/hierarchy/items_api.rb b/lib/api/v3/custom_fields/hierarchy/items_api.rb index 7907839f4b0b..101e6fca6008 100644 --- a/lib/api/v3/custom_fields/hierarchy/items_api.rb +++ b/lib/api/v3/custom_fields/hierarchy/items_api.rb @@ -38,7 +38,10 @@ def flatten_tree_hash(hash) flat_list = [] queue = [hash] + # From the service we get a hashed tree like this: # {:a => {:b => {:c1 => {:d1 => {}}, :c2 => {:d2 => {}}}, :b2 => {}}} + # We flatten it depth first to this result list: + # [:a, :b, :c1, :d1, :c2, :d2, :b2] while queue.any? current = queue.shift @@ -60,10 +63,20 @@ def item_list(query) start_item = ::CustomField::Hierarchy::Item.find_by(id: validation[:parent]) || hierarchy_root depth = validation[:depth] || -1 + flat_tree(start_item, depth) + end + + def flat_tree(item, depth) sub_tree = ::CustomFields::Hierarchy::HierarchicalItemService .new - .hashed_subtree(item: start_item, depth:) - .value! + .hashed_subtree(item:, depth:) + .either( + ->(value) { value }, + ->(error) do + msg = "#{I18n.t('api_v3.errors.code_500')} #{error}" + raise ::API::Errors::InternalError.new(msg) + end + ) flatten_tree_hash(sub_tree) end