All files / domains/schema compiler.ts

95.83% Statements 23/24
83.33% Branches 10/12
100% Functions 5/5
95.83% Lines 23/24

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 85 86 8717x 17x 17x 17x 17x   6x 1x   5x 1x         6x         12x 6x 6x 6x   12x 12x 7x   5x           6x 6x 6x 4x         17x                                                                                      
import {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLFieldConfig,
  GraphQLOutputType,
  isOutputType,
} from 'graphql';
import { queryFieldsRegistry, mutationFieldsRegistry, schemaRegistry } from './registry';
import { SchemaError } from './error';
import { mapObject } from 'services/utils';
 
function validateSchemaTarget(target: Function) {
  if (!schemaRegistry.has(target)) {
    throw new SchemaError(target, `Schema target must be registered with @Schema`);
  }
I
  if (queryFieldsRegistry.isEmpty(target)) {
    throw new SchemaError(
      target,
      `Schema must have at least one field registered with @Query`,
    );
  }
}
 
function validateRootFieldType(
  target: Function,
  fieldName: string,
  type: GraphQLOutputType,
  rootFieldType: string,
) {
  // return true;
  if (!isOutputType(type)) {
    throw new SchemaError(
      target,
      `Root field ${rootFieldType}.${fieldName} is not compiled to GraphQLOutputType. Compiled type is '${type}'.`,
    );
  }
}
 
interface FieldsData {
  [fieldName: string]: () => GraphQLFieldConfig<any, any>;
}
 
function compileSchemaRootFieldIfNotEmpty(
  target: Function,
  name: string,
  fields: FieldsData,
) {
  const compiledFields = mapObject(fields, (compiler, fieldName) => {
    const compiledField = compiler();
    validateRootFieldType(target, fieldName, compiledField.type, name);
    return compiledField;
  });
 
  const isEmpty = Object.keys(compiledFields).length <= 0;
 
  if (isEmpty) {
    return null;
  }
 
  return new GraphQLObjectType({
    name,
    fields: compiledFields,
  });
}
 
export function compileSchema(target: Function) {
  const query = compileSchemaRootFieldIfNotEmpty(
    target,
    'Query',
    queryFieldsRegistry.getAll(target),
  );
 
  const mutation = compileSchemaRootFieldIfNotEmpty(
    target,
    'Mutation',
    mutationFieldsRegistry.getAll(target),
  );
 
  validateSchemaTarget(target);
 
  return new GraphQLSchema({
    query: query || undefined,
    mutation: mutation || undefined,
  });
}