All files / src/definitions interfacetype.ts

100% Statements 13/13
85.71% Branches 6/7
100% Functions 3/3
100% Lines 12/12
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  8x 8x 8x 8x 8x 8x 8x 8x 8x   8x   8x           8x                                                                                    
/**
 * Copyright (c) 2017-present, Graphene.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
import {
  GraphQELResolveInfo,
  GraphQLTypeResolver,
  GraphQLObjectType,
  GraphQLInterfaceType
} from "graphql";
import {
  UnmountedFieldMap,
  getFields,
  assertFields,
  getGraphQLType,
  setGraphQLType,
  getDescription,
  mountFields
} from "./../reflection";
 
// The provided configuration type when creating an Interface.
export type InterfaceTypeConfig = {
  name?: string;
  description?: string;
  resolveType?: (root?: any, context?: any, info?: GraphQLResolveInfo) => any;
};
 
export const InterfaceType = (opts: InterfaceTypeConfig = {}) => <
  T extends { new (...args: any[]): any }
>(
  target: T
): T => {
  const fields: UnmountedFieldMap = getFields(target);
  assertFields(target, fields);
 
  const resolveType: GraphQLTypeResolver<any, any> = (
    root?: any,
    context?: any,
    info?: GraphQLResolveInfo
  ): string | GraphQLObjectType | Promise<string | GraphQLObjectType> => {
    if (opts.resolveType) {
      root = opts.resolveType(root, context, info);
    }
    return <GraphQLObjectType>getGraphQLType(root);
  };
 
  setGraphQLType(
    target,
    new GraphQLInterfaceType({
      name: opts.name || target.name,
      description: opts.description || getDescription(target),
      resolveType: resolveType,
      fields: mountFields(fields)
    })
  );
 
  return target;
};