All files / domains/objectType/compiler objectType.ts

79.31% Statements 23/29
75% Branches 9/12
83.33% Functions 5/6
81.48% Lines 22/27
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 539x               9x 9x 9x 9x 9x 9x   38x 2x   36x 30x       50x 12x   38x 36x 36x   9x   51x 1x   50x 50x   9x                            
import { GraphQLObjectType } from 'graphql';
import { ObjectTypeError, objectTypeRegistry } from '../index';

import { compileAllFields, fieldsRegistry } from 'domains/field';
import { createCachedThunk } from 'services/utils';
 
const compileOutputTypeCache = new WeakMap<Function, GraphQLObjectType>();
 
export interface TypeOptions {
  name: string;
  description?: string;
}
 
function createTypeFieldsGetter(target: Function) {
  if (fieldsRegistry.isEmpty(target)) {
    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 @Type decorator`,
    );
  }
 
  const compiler = objectTypeRegistry.get(target);
  return compiler();
}