All files / domains/schema compiler.ts

96.88% Statements 31/32
78.57% Branches 11/14
100% Functions 4/4
96.88% Lines 31/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 8520x 20x 20x 20x 20x 20x   25x 25x 32x 32x 18x 18x   18x 1x   17x     25x 32x 32x   24x 24x 11x   13x           14x 14x     14x 13x 12x 12x 2x   10x         20x                                                                      
import { GraphQLSchema, GraphQLObjectType, GraphQLFieldConfig } from 'graphql';
import {
  queryFieldsRegistry,
  mutationFieldsRegistry,
  RootFieldsRegistry,
} from './registry';
import { SchemaRootError } from './error';
import { showDeprecationWarning } from '~/services/utils';
 
import { validateSchemaRoots } from "./services";
 
export interface CompileSchemaOptions {
  roots: Function[];
}
 
function getAllRootFieldsFromRegistry(
  roots: Function[],
  registry: RootFieldsRegistry,
  name: 'Query' | 'Mutation',
): GraphQLObjectType {
  const allRootFields: { [key: string]: GraphQLFieldConfig<any, any> } = {};
  for (let root of roots) {
    const rootFields = registry.getAll(root);
    Object.keys(rootFields).forEach(fieldName => {
      const fieldConfigGetter = rootFields[fieldName];
      const fieldConfig = fieldConfigGetter();
 
      // throw error if root field with this name is already registered
      if (!!allRootFields[fieldName]) {
        throw new SchemaRootError(
          root,
          `Duplicate of root field name: '${fieldName}'. Seems this name is also used inside other schema root.`,
        );
      }
      allRootFields[fieldName] = fieldConfig;
    I});
  }
 
  const isEmpty = Object.keys(allRootFields).length < 1;
 
  if (isEmpty) {
    return null;
  }
 
  return new GraphQLObjectType({
    name,
    fields: allRootFields,
  });
}
 
export function compileSchema(config: CompileSchemaOptions | Function) {
  const roots = typeof config === 'function' ? [config] : config.roots;
 
  if (typeof config === 'function') {
    showDeprecationWarning(
      `Passing schema root to compileSchema is deprecated. Use config object with 'roots' field. compileSchema(SchemaRoot) --> compileSchema({ roots: [SchemaRoot] })`,
      config,
    );
  }
 
  validateSchemaRoots(roots);
 
  const query = getAllRootFieldsFromRegistry(
    roots,
    queryFieldsRegistry,
    'Query',
  );
  const mutation = getAllRootFieldsFromRegistry(
    roots,
    mutationFieldsRegistry,
    'Mutation',
  );
 
  if (!query) {
    throw new Error(
      'At least one of schema roots must have @Query root field.',
    );
  }
 
  return new GraphQLSchema({
    query: query || undefined,
    mutation: mutation || undefined,
  });
}