All files / domains/schema compiler.ts

100% Statements 20/20
100% Branches 6/6
100% Functions 5/5
100% Lines 20/20
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 679x 9x 9x 9x 9x   4x 1x   3x 1x       2x 1x       2x 2x 2x 1x   1x           4x 2x 1x       9x                                                            
import {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLFieldConfig,
  GraphQLOutputType,
  isCompositeType,
} from 'graphql';
import { queryFieldsRegistry, schemaRegistry } from './registry';
import { SchemaError } from './error';
import { mapObject, convertObjectToArray, isObjectType } from 'services/utils';
 
function validateSchemaTarget(target: Function) {
  if (!schemaRegistry.has(target)) {
    throw new SchemaError(target, `Schema target must be registered with @Schema`);
  }
  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,
) {
  if (!isObjectType(type)) {
    throw new SchemaError(
      target,
      `Root field ${rootFieldType}.${fieldName} is not compiled to GraphQLObjectType. Compiled type is '${type}'.`,
    );
  }
}
 
interface FieldsData {
  [fieldName: string]: () => GraphQLFieldConfig<any, any>;
}
 
function compileSchemaRootField(target: Function, name: string, fields: FieldsData) {
  const compiledFields = mapObject(fields, (compiler, fieldName) => {
    const compiledField = compiler();
    validateRootFieldType(target, fieldName, compiledField.type, name);
    return compiledField;
  });
 
  return new GraphQLObjectType({
    name,
    fields: compiledFields,
  });
}
 
export function compileSchema(target: Function) {
  validateSchemaTarget(target);
  const query = compileSchemaRootField(
    target,
    'Query',
    queryFieldsRegistry.getAll(target),
  );
 
  return new GraphQLSchema({
    query,
  });
}