All files / src/definitions objecttype.ts

100% Statements 19/19
92.31% Branches 12/13
100% Functions 4/4
100% Lines 18/18
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 67 68 69 70 71 72 73 74  8x 8x 8x 19x 19x 8x 8x 1x   7x   18x 18x 7x 7x 7x   18x 18x 17x           17x                                                                                              
/**
 * 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 { GraphQLInterfaceType, GraphQLObjectType } from "graphql";
import {
  getGraphQLType,
  UnmountedFieldMap,
  getFields,
  assertFields,
  setGraphQLType,
  getDescription,
  mountFields
} from "./../reflection";
 
// The provided configuration type when creating an ObjectType.
export type ObjectTypeConfig = {
  name?: string;
  description?: string;
  interfaces?: any[];
};
 
export const ObjectType = (opts: ObjectTypeConfig = {}) => <
  T extends { new (...args: any[]): any }
>(
  target: T
): T => {
  // save a reference to the original constructor
  const interfaces: GraphQLInterfaceType[] = (opts.interfaces || []).map(
    iface => {
      const ifaceType = getGraphQLType(iface);
      if (!(ifaceType instanceof GraphQLInterfaceType)) {
        throw new Error(`Provided interface ${ifaceType} is not valid`);
      }
      return ifaceType;
    }
  );
 
  let allInterfaceFields: UnmountedFieldMap = {};
 
  (opts.interfaces || []).forEach((_, index) => {
    const iface = (opts.interfaces || [])[index];
    const ifaceFields: UnmountedFieldMap = getFields(iface);
    allInterfaceFields = {
      ...allInterfaceFields,
      ...ifaceFields
    };
  });
 
  const fields: UnmountedFieldMap = {
    // First we introduce the fields from the interfaces that we inherit
    ...allInterfaceFields,
    // Then we retrieve the fields for the current type
    ...getFields(target)
  };
 
  assertFields(target, fields);
 
  setGraphQLType(
    target,
    new GraphQLObjectType({
      name: opts.name || target.name,
      description: opts.description || getDescription(target),
      interfaces: interfaces,
      fields: mountFields(fields)
    })
  );
 
  return target;
};