All files / domains/objectType/compiler objectType.ts

81.25% Statements 26/32
75% Branches 9/12
85.71% Functions 6/7
83.33% Lines 25/30

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 5817x               17x 17x 17x 17x 17x 17x   63x 63x 124x   63x 4x   59x 49x       82x 19x   63x 59x 59x   17x   84x 2x   82x 82x   17x                              
import { GraphQLObjectType } from 'graphql';
import { ObjectTypeError, objectTypeRegistry } from '../index';

import { compileAllFields, fieldsRegistry } from 'domains/field';
import { createCachedThunk, getClassWithAllParentClasses } from 'services/utils';
 
const compileOutputTypeCache = new WeakMap<Function, GraphQLObjectType>();
 
export interface TypeOptions {
  name: string;
  description?: string;
}
 
function createTypeFieldsGetter(target: Function) {
  const targetWithParents = getClassWithAllParentClasses(target);
  const hasFields = targetWithParents.some(ancestor => {
    return !fieldsRegistry.isEmpty(ancestor);
  });
 
  if (!hasFields) {
    throw new ObjectTypeError(target, `There are no fields inside this type.`);
  }
 
  return createCachedThunk(() => {
    return compileAllFields(target);
  });
}
 
export function compileObjectTypeWithConfig(
  target: Function,
  config: TypeOptions,
): GraphQLObjectType {
  if (compileOutputTypeCache.has(target)) {
    return compileOutputTypeCache.get(target);
  }
 
  const compiled = new GraphQLObjectType({
    ...config,
    isTypeOf: value => value instanceof target,
    fields: createTypeFieldsGetter(target),
  });
 
  compileOutputTypeCache.set(target, compiled);
  return compiled;
}
 
export function compileObjectType(target: Function) {
  if (!objectTypeRegistry.has(target)) {
    throw new ObjectTypeError(
      target,
      `Class is not registered. Make sure it's decorated with @ObjectType decorator`,
    );
  }
 
  const compiler = objectTypeRegistry.get(target);
  return compiler();
}