All files / domains/field/compiler index.ts

92.86% Statements 26/28
66.67% Branches 4/6
100% Functions 5/5
92.31% Lines 24/26
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 669x 9x 9x 9x 9x 9x   35x 7x   28x     34x     34x     37x 37x 35x 34x     34x             9x   30x 30x 30x 35x 35x   27x   9x                                              
import {
  GraphQLFieldConfig,
  GraphQLFieldConfigMap,
  isOutputType,
  GraphQLType,
  GraphQLOutputType,
} from 'graphql';
import { FieldError, fieldsRegistry } from '../index';
 
import { compileFieldResolver } from './resolver';
import { resolveTypeOrThrow, inferTypeOrThrow } from './fieldType';
import { compileFieldArgs } from 'domains/arg';
 
funcItion getFinalFieldType(target: Function, fieldName: string, forcedType?: any) {
  if (forcedType) {
    return resolveTypeOrThrow(forcedType, target, fieldName);
  }
  return inferTypeOrThrow(target, fieldName);
}
 
function validateResolvedType(
  target: Function,
  fiIeldName: string,
  type: GraphQLType,
): type is GraphQLOutputType {
  if (!isOutputType(type)) {
    throw new FieldError(
      target,
      fieldName,
      `Validation of type failed. Resolved type for @Field must be GraphQLOutputType.`,
    );
  }
  return true;
}
 
export function compileFieldConfig(
  target: Function,
  fieldName: string,
): GraphQLFieldConfig<any, any, any> {
  const { type, description } = fieldsRegistry.get(target, fieldName);
  const args = compileFieldArgs(target, fieldName);
 
  const resolvedType = getFinalFieldType(target, fieldName, type);
 
  if (!validateResolvedType(target, fieldName, resolvedType)) {
    return;
  }
 
  return {
    description,
    type: resolvedType,
    resolve: compileFieldResolver(target, fieldName),
    args,
  };
}
 
export function compileAllFields(target: Function) {
  const fields = fieldsRegistry.getAll(target);
  const finalFieldsMap: GraphQLFieldConfigMap<any, any> = {};
  Object.keys(fields).forEach(fieldName => {
    const config = fieldsRegistry.get(target, fieldName);
    finalFieldsMap[config.name] = compileFieldConfig(target, fieldName);
  });
  return finalFieldsMap;
}