extractFragments static method

Set<FragmentDefinitionNode> extractFragments(
  1. SelectionSetNode? selectionSet,
  2. List<FragmentDefinitionNode> fragmentsCommon
)

Extracts fragments from a selection set recursively, including nested fragments.

This method traverses the selection set and finds all fragment spreads, then recursively extracts fragments from those fragment definitions. It also handles inline fragments by recursively processing their selection sets.

Implementation

static Set<FragmentDefinitionNode> extractFragments(
  SelectionSetNode? selectionSet,
  List<FragmentDefinitionNode> fragmentsCommon,
) {
  final result = <FragmentDefinitionNode>{};

  if (selectionSet == null) {
    return result;
  }

  // Process field selections recursively
  selectionSet.selections.whereType<FieldNode>().forEach((selection) {
    result.addAll(extractFragments(selection.selectionSet, fragmentsCommon));
  });

  // Process inline fragments recursively
  selectionSet.selections.whereType<InlineFragmentNode>().forEach((
    selection,
  ) {
    result.addAll(extractFragments(selection.selectionSet, fragmentsCommon));
  });

  // Process fragment spreads and their nested fragments
  selectionSet.selections.whereType<FragmentSpreadNode>().forEach((
    selection,
  ) {
    final fragmentDefinitions = fragmentsCommon.where(
      (fragmentDefinition) =>
          fragmentDefinition.name.value == selection.name.value,
    );

    result.addAll(fragmentDefinitions);

    // Recursively extract fragments from the found fragment definitions
    for (final fragmentDefinition in fragmentDefinitions) {
      result.addAll(
        extractFragments(fragmentDefinition.selectionSet, fragmentsCommon),
      );
    }
  });

  return result;
}