generateLibrarySpec function

Spec generateLibrarySpec(
  1. LibraryDefinition definition
)

Gathers and generates a Spec of a whole query/mutation and its dependencies into a single library file.

Implementation

Spec generateLibrarySpec(LibraryDefinition definition) {
  final importDirectives = [
    Directive.import('package:json_annotation/json_annotation.dart'),
    Directive.import('package:equatable/equatable.dart'),
    Directive.import('package:gql/ast.dart'),
  ];

  if (definition.queries.any((q) => q.generateHelpers)) {
    importDirectives.insertAll(
      0,
      [
        Directive.import('package:artemis/artemis.dart'),
      ],
    );
  }

  importDirectives.addAll(definition.customImports
      .map((customImport) => Directive.import(customImport)));

  final bodyDirectives = <Spec>[
    CodeExpression(Code('part \'${definition.basename}.g.dart\';')),
  ];

  final uniqueDefinitions = definition.queries
      .map((e) => e.classes.map((e) => e))
      .expand((e) => e)
      .fold<Map<String?, Definition>>(<String?, Definition>{}, (acc, element) {
    acc[element.name.name] = element;

    return acc;
  }).values;

  final fragments = uniqueDefinitions.whereType<FragmentClassDefinition>();
  final classes = uniqueDefinitions.whereType<ClassDefinition>();
  final enums = uniqueDefinitions.whereType<EnumDefinition>();

  bodyDirectives.addAll(fragments.map(fragmentClassDefinitionToSpec));
  bodyDirectives.addAll(
      classes.map((cDef) => classDefinitionToSpec(cDef, fragments, classes)));
  bodyDirectives.addAll(enums.map(enumDefinitionToSpec));

  for (final queryDef in definition.queries) {
    if (queryDef.inputs.isNotEmpty &&
        (queryDef.generateHelpers || queryDef.generateQueries)) {
      bodyDirectives.add(generateArgumentClassSpec(queryDef));
    }

    if (queryDef.generateHelpers || queryDef.generateQueries) {
      bodyDirectives.add(generateQuerySpec(queryDef));
    }

    if (queryDef.generateHelpers) {
      bodyDirectives.add(generateQueryClassSpec(queryDef));
    }
  }

  return Library(
    (b) => b
      ..directives.addAll(importDirectives)
      ..body.addAll(bodyDirectives),
  );
}