graphql#GraphQLString TypeScript Examples

The following examples show how to use graphql#GraphQLString. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From proto2graphql with MIT License 7 votes vote down vote up
ScalarTypeMap = {
  double: GraphQLFloat,
  float: GraphQLFloat,
  int32: GraphQLInt,
  int64: GraphQLInt,
  uint32: GraphQLInt,
  uint64: GraphQLInt,
  sint32: GraphQLInt,
  sint64: GraphQLInt,
  fixed32: GraphQLInt,
  fixed64: GraphQLInt,
  sfixed32: GraphQLInt,
  sfixed64: GraphQLInt,
  bool: GraphQLBoolean,
  string: GraphQLString,
  bytes: GraphQLString
}
Example #2
Source File: grades.ts    From peterportal-public-api with MIT License 6 votes vote down vote up
gradeDistributionCollectionType: GraphQLObjectType = new GraphQLObjectType({
  name: 'GradeDistributionCollection',

  fields: () => ({
    aggregate: { type: gradeDistributionCollectionAggregateType },
    grade_distributions: {type: new GraphQLList(gradeDistributionType)},
    instructors: { 
      type: new GraphQLList(GraphQLString),
      description: "List of instructors present in the Grade Distribution Collection" 
    }
  })
})
Example #3
Source File: getType.test.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
describe('getType', () => {
  const testObj = new GraphQLObjectType({
    name: 'Address',
    fields: {
      street: { type: GraphQLString },
      number: { type: GraphQLInt },
      requiredInt: { type: new GraphQLNonNull(GraphQLInt) },
      listOfInt: { type: new GraphQLList(GraphQLInt) },
      listOfNonNullInt: { type: new GraphQLNonNull(new GraphQLList(GraphQLInt)) },
    },
  });

  it('should return string type for street', () => {
    expect(getType(testObj.getFields().street.type)).toEqual(GraphQLString);
  });

  it('should return integer type for number', () => {
    expect(getType(testObj.getFields().number.type)).toEqual(GraphQLInt);
  });

  it('should return integer type for a Non-Null integer', () => {
    expect(getType(testObj.getFields().requiredInt.type)).toEqual(GraphQLInt);
  });

  it('should return integer type for list of integer type', () => {
    expect(getType(testObj.getFields().listOfInt.type)).toEqual(GraphQLInt);
  });

  it('should return integer type for a list of non null integer type', () => {
    expect(getType(testObj.getFields().listOfNonNullInt.type)).toEqual(GraphQLInt);
  });
});
Example #4
Source File: schema-resolver.ts    From graphql-mesh with MIT License 6 votes vote down vote up
private resolveInputType(soapType: SoapType): GraphQLInputType {
    if (this.alreadyResolved.has(soapType)) {
      return this.alreadyResolved.get(soapType);
    }

    if (typeof soapType === 'string') {
      const customType: GraphQLInputType = this.options.customResolver.inputType(soapType);
      if (customType) {
        this.alreadyResolved.set(soapType, customType);
        return customType;
      }
    } else if (soapType?.name && soapType?.fields?.length > 0) {
      const objectType: GraphQLInputObjectType = this.createObjectType(soapType);
      if (objectType) {
        this.alreadyResolved.set(soapType, objectType);
        return objectType;
      }
    }

    this.logger.warn(`could not resolve input type '${soapType}'; using GraphQLString`);
    this.alreadyResolved.set(soapType, GraphQLString);
    return GraphQLString;
  }
Example #5
Source File: types.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export function typeNameFromGraphQLType(
  context: LegacyCompilerContext,
  type: GraphQLType,
  bareTypeName?: string | null,
  nullable = true
): string {
  if (isNonNullType(type)) {
    return typeNameFromGraphQLType(context, type.ofType, bareTypeName, false);
  }

  let typeName;
  if (isListType(type)) {
    typeName = `Array< ${typeNameFromGraphQLType(context, type.ofType, bareTypeName, true)} >`;
  } else if (type instanceof GraphQLScalarType) {
    typeName =
      builtInScalarMap[type.name] ||
      appSyncScalars[type.name] ||
      (context.options.passthroughCustomScalars ? context.options.customScalarsPrefix + type.name : builtInScalarMap[GraphQLString.name]);
  } else {
    typeName = bareTypeName || type.name;
  }

  return nullable ? typeName + ' | null' : typeName;
}
Example #6
Source File: index.test.ts    From hono with MIT License 6 votes vote down vote up
QueryRootType = new GraphQLObjectType({
  name: 'QueryRoot',
  fields: {
    test: {
      type: GraphQLString,
      args: {
        who: { type: GraphQLString },
      },
      resolve: (_root, args: { who?: string }) => 'Hello ' + (args.who ?? 'World'),
    },
    thrower: {
      type: GraphQLString,
      resolve() {
        throw new Error('Throws!')
      },
    },
  },
})
Example #7
Source File: instructor.ts    From peterportal-public-api with MIT License 6 votes vote down vote up
instructorType: GraphQLObjectType = new GraphQLObjectType({
  name: 'Instructor',
  
  fields: () => ({
    name: { type: GraphQLString },
    shortened_name: { 
      type: GraphQLString, 
      description: "Name as it appears on webreg. Follows the format: `DOE, J.`",
      resolve: (instructor) => {
        if (instructor.shortened_name) {
          return instructor.shortened_name
        } else {
          // If the shortened_name wasn't provided, 
          // we can construct it from the name.
          const name_parts = instructor.name.split(' ');
          return `${name_parts[name_parts.length-1]}, ${name_parts[0][0]}.`.toUpperCase()
        }
      }
    },
    ucinetid: { type: GraphQLString },
    email: {type: GraphQLString },
    title: { type: GraphQLString },
    department: { type: GraphQLString },
    schools: { type: new GraphQLList(GraphQLString) },
    related_departments: { type: new GraphQLList(GraphQLString) },
    course_history: { 
      type: new GraphQLList(courseType),
      resolve: (instructor) => {
        return getInstructor(instructor.ucinetid)["course_history"].map(course_id => getCourse(course_id.replace(/ /g, "")));
      }
    }
  })
})
Example #8
Source File: buildMutationInputType.ts    From payload with MIT License 6 votes vote down vote up
getCollectionIDType = (config: SanitizedCollectionConfig): GraphQLScalarType => {
  const idField = config.fields.find((field) => fieldAffectsData(field) && field.name === 'id');
  if (!idField) return GraphQLString;
  switch (idField.type) {
    case 'number':
      return GraphQLInt;
    default:
      return GraphQLString;
  }
}
Example #9
Source File: graphql_tools.ts    From graphql-mesh with MIT License 6 votes vote down vote up
/**
 * Returns empty GraphQLObjectType.
 */
export function getEmptyObjectType(name: string): GQObjectType {
  return new GraphQLObjectType({
    name: name + 'Placeholder',
    description: 'Placeholder object',
    fields: {
      message: {
        type: GraphQLString,
        description: 'Placeholder field',
        resolve: () => {
          return 'This is a placeholder field.';
        },
      },
    },
  });
}
Example #10
Source File: GraphqlTypeInterpreter.test.ts    From aloxide with Apache License 2.0 6 votes vote down vote up
describe('test GraphqlTypeInterpreter', () => {
  describe('interpret()', () => {
    const intepreter = new GraphqlTypeInterpreter();

    it('should throw error when Field Type is not support', () => {
      expect(() => {
        // @ts-ignore
        intepreter.interpret('not supported type');
      }).toThrowError('unknow type');
    });

    it('should return Graphql Int when the input is uint', () => {
      expect(intepreter.interpret(FieldTypeEnum.uint16_t)).toBe(GraphQLInt);
      expect(intepreter.interpret(FieldTypeEnum.uint32_t)).toBe(GraphQLInt);
      expect(intepreter.interpret(FieldTypeEnum.uint64_t)).toBe(GraphQLInt);
    });

    it('should return Graphql Float when the input is number or double', () => {
      expect(intepreter.interpret(FieldTypeEnum.number)).toBe(GraphQLFloat);
      expect(intepreter.interpret(FieldTypeEnum.double)).toBe(GraphQLFloat);
    });

    it('should return Graphql Boolean when the input is boolean', () => {
      expect(intepreter.interpret(FieldTypeEnum.bool)).toBe(GraphQLBoolean);
    });

    it('should return Graphql String when the input is string', () => {
      expect(intepreter.interpret(FieldTypeEnum.account)).toBe(GraphQLString);
      expect(intepreter.interpret(FieldTypeEnum.string)).toBe(GraphQLString);
    });
  });
});
Example #11
Source File: schema.ts    From apollo-server-vercel with MIT License 6 votes vote down vote up
personType = new GraphQLObjectType({
  name: `PersonType`,
  fields: {
    firstName: {
      type: GraphQLString
    },
    lastName: {
      type: GraphQLString
    }
  }
})
Example #12
Source File: GraphqlTypeInterpreter.ts    From aloxide with Apache License 2.0 6 votes vote down vote up
interpret(input: FieldTypeEnum): GraphQLScalarType {
    let type: GraphQLScalarType;

    switch (input) {
      case FieldTypeEnum.uint16_t:
      case FieldTypeEnum.uint32_t:
      case FieldTypeEnum.uint64_t:
        type = GraphQLInt;
        break;
      case FieldTypeEnum.number:
      case FieldTypeEnum.double:
        type = GraphQLFloat;
        break;
      case FieldTypeEnum.bool:
        type = GraphQLBoolean;
        break;
      case FieldTypeEnum.account:
      case FieldTypeEnum.string:
        type = GraphQLString;
        break;
      default:
        throw new Error(`unknow type ${type}`);
    }

    return type;
  }
Example #13
Source File: schema.ts    From apollo-server-vercel with MIT License 6 votes vote down vote up
mutationType = new GraphQLObjectType({
  name: `MutationType`,
  fields: {
    testMutation: {
      type: GraphQLString,
      args: { echo: { type: GraphQLString } },
      resolve(_, { echo }): string {
        return `not really a mutation, but who cares: ${String(echo)}`;
      }
    },
    testPerson: {
      type: personType,
      args: {
        firstName: {
          type: new GraphQLNonNull(GraphQLString)
        },
        lastName: {
          type: new GraphQLNonNull(GraphQLString)
        }
      },
      resolve(_, args): typeof args {
        return args;
      }
    },
    testRootValue: {
      type: GraphQLString,
      resolve(rootValue): typeof rootValue {
        return rootValue;
      }
    }
  }
})
Example #14
Source File: types.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
builtInScalarMap = {
  [GraphQLString.name]: 'string',
  [GraphQLInt.name]: 'number',
  [GraphQLFloat.name]: 'number',
  [GraphQLBoolean.name]: 'boolean',
  [GraphQLID.name]: 'string',
}
Example #15
Source File: init.ts    From payload with MIT License 5 votes vote down vote up
function registerPreferences(): void {
  const {
    findOne, update, delete: deleteOperation,
  } = this.operations.preferences;


  const valueType = GraphQLJSON;

  const preferenceType = new GraphQLObjectType({
    name: 'Preference',
    fields: {
      key: {
        type: GraphQLNonNull(GraphQLString),
      },
      value: { type: valueType },
      createdAt: { type: new GraphQLNonNull(DateTimeResolver) },
      updatedAt: { type: new GraphQLNonNull(DateTimeResolver) },
    },
  });

  this.Query.fields.Preference = {
    type: preferenceType,
    args: {
      key: { type: GraphQLString },
    },
    resolve: (_, { key }, context) => {
      const { user } = context.req;
      return findOne({ key, user, req: context.req });
    },
  };

  this.Mutation.fields.updatePreference = {
    type: preferenceType,
    args: {
      key: { type: new GraphQLNonNull(GraphQLString) },
      value: { type: valueType },
    },
    resolve: (_, { key, value }, context) => {
      const { user } = context.req;
      return update({ key, user, req: context.req, value });
    },
  };

  this.Mutation.fields.deletePreference = {
    type: preferenceType,
    args: {
      key: { type: new GraphQLNonNull(GraphQLString) },
    },
    resolve: (_, { key }, context) => {
      const { user } = context.req;
      return deleteOperation({ key, user, req: context.req });
    },
  };
}
Example #16
Source File: generateSchema.ts    From davinci with MIT License 5 votes vote down vote up
scalarDict = {
	number: GraphQLFloat,
	string: GraphQLString,
	boolean: GraphQLBoolean,
	object: GraphQLJSON,
	date: GraphQLDateTime
}
Example #17
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
builtInScalarMap = {
  [GraphQLString.name]: 'String',
  [GraphQLInt.name]: 'Int',
  [GraphQLFloat.name]: 'Double',
  [GraphQLBoolean.name]: 'Bool',
  [GraphQLID.name]: 'GraphQLID',
}
Example #18
Source File: schedule.ts    From peterportal-public-api with MIT License 5 votes vote down vote up
courseOfferingType: GraphQLObjectType = new GraphQLObjectType({
  name: "CourseOffering",

  fields: () => ({
    year: { type: GraphQLString },
    quarter: { type: GraphQLString },
    instructors: { 
      type: new GraphQLList(instructorType),
      resolve: (offering) => {
        return offering.instructors.map((name: string) => {
          
          //Fetch all possible ucinetids from the instructor.
          let ucinetids : string[] = getUCINetIDFromName(name);
          
          //If only one ucinetid exists and it's in the instructor cache, 
          //then we can return the instructor for it.
          if (ucinetids && ucinetids.length == 1) { 
            const instructor = getInstructor(ucinetids[0]);
            if (instructor) { return instructor; }
          }
          //If there is more than one and the course exists, 
          //use the course to figure it out.
          else if (ucinetids && ucinetids.length > 1 && offering.course) {

              //Filter our instructors by those with related departments.
              let course_dept = offering.course.department;
              let instructors = ucinetids.map(id => getInstructor(id)).filter( temp => temp.related_departments.includes(course_dept));
              
              //If only one is left and it's in the instructor cache, we can return it.
              if (instructors.length == 1) {
                return instructors[0];
              } else {
                //Filter instructors by those that taught the course before.
                instructors = instructors.filter( inst => {
                  return inst.course_history.map((course) => course.replace(/ /g, "")).includes(offering.course.id);
                });
              
                //If only one is left and it's in the instructor cache, we can return it.
                if (instructors.length == 1) { 
                  return instructors[0];
                }
              }
          }
          
          //If we haven't found any instructors, then just return the shortened name.
          return {shortened_name: name};
        })
      }
    }, 
    final_exam: { type: GraphQLString },
    max_capacity: { type: GraphQLFloat },
    meetings: { type: new GraphQLList(meetingType) },
    num_section_enrolled: { type: GraphQLFloat },
    num_total_enrolled: { type: GraphQLFloat },
    num_new_only_reserved: { type: GraphQLFloat },
    num_on_waitlist: { 
      type: GraphQLFloat, 
      resolve: (offering) => {
          return offering.num_on_waitlist === 'n/a' ? null : offering.num_on_waitlist;
        } 
    },
    num_requested: { type: GraphQLFloat },
    restrictions: { type: GraphQLString },
    section: { type: sectionInfoType },  
    status: { type: GraphQLString },
    units: { type: GraphQLString },
    course: { 
      type: courseType,
      resolve: (offering) => {
        // Get the course from the cache.
        const course = getCourse(offering.course.id);
        // If it's not in our cache, return whatever information was provided.
        // Usually, it will at least have id, department, and number
        return course ? course : offering.course;
      }
    }
  })
})
Example #19
Source File: typeNameFromGraphQLType.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
describe('Swift code generation: Types', () => {
  let helpers: Helpers;

  beforeEach(() => {
    helpers = new Helpers({});
  });

  describe('#typeNameFromGraphQLType()', () => {
    it('should return String? for GraphQLString', () => {
      expect(helpers.typeNameFromGraphQLType(GraphQLString)).toBe('String?');
    });

    it('should return String for GraphQLNonNull(GraphQLString)', () => {
      expect(helpers.typeNameFromGraphQLType(new GraphQLNonNull(GraphQLString))).toBe('String');
    });

    it('should return [String?]? for GraphQLList(GraphQLString)', () => {
      expect(helpers.typeNameFromGraphQLType(new GraphQLList(GraphQLString))).toBe('[String?]?');
    });

    it('should return [String?] for GraphQLNonNull(GraphQLList(GraphQLString))', () => {
      expect(helpers.typeNameFromGraphQLType(new GraphQLNonNull(new GraphQLList(GraphQLString)))).toBe('[String?]');
    });

    it('should return [String]? for GraphQLList(GraphQLNonNull(GraphQLString))', () => {
      expect(helpers.typeNameFromGraphQLType(new GraphQLList(new GraphQLNonNull(GraphQLString)))).toBe('[String]?');
    });

    it('should return [String] for GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString)))', () => {
      expect(helpers.typeNameFromGraphQLType(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))))).toBe('[String]');
    });

    it('should return [[String?]?]? for GraphQLList(GraphQLList(GraphQLString))', () => {
      expect(helpers.typeNameFromGraphQLType(new GraphQLList(new GraphQLList(GraphQLString)))).toBe('[[String?]?]?');
    });

    it('should return [[String?]]? for GraphQLList(GraphQLNonNull(GraphQLList(GraphQLString)))', () => {
      expect(helpers.typeNameFromGraphQLType(new GraphQLList(new GraphQLNonNull(new GraphQLList(GraphQLString))))).toBe('[[String?]]?');
    });

    it('should return Int? for GraphQLInt', () => {
      expect(helpers.typeNameFromGraphQLType(GraphQLInt)).toBe('Int?');
    });

    it('should return Double? for GraphQLFloat', () => {
      expect(helpers.typeNameFromGraphQLType(GraphQLFloat)).toBe('Double?');
    });

    it('should return Bool? for GraphQLBoolean', () => {
      expect(helpers.typeNameFromGraphQLType(GraphQLBoolean)).toBe('Bool?');
    });

    it('should return GraphQLID? for GraphQLID', () => {
      expect(helpers.typeNameFromGraphQLType(GraphQLID)).toBe('GraphQLID?');
    });

    it('should return String? for a custom scalar type', () => {
      expect(helpers.typeNameFromGraphQLType(new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe('String?');
    });

    it('should return a passed through custom scalar type with the passthroughCustomScalars option', () => {
      helpers.options.passthroughCustomScalars = true;
      helpers.options.customScalarsPrefix = '';

      expect(helpers.typeNameFromGraphQLType(new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe(
        'CustomScalarType?'
      );
    });

    it('should return a passed through custom scalar type with a prefix with the customScalarsPrefix option', () => {
      helpers.options.passthroughCustomScalars = true;
      helpers.options.customScalarsPrefix = 'My';

      expect(helpers.typeNameFromGraphQLType(new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe(
        'MyCustomScalarType?'
      );
    });
  });
});
Example #20
Source File: Generator.ts    From graphql-ts-client with MIT License 5 votes vote down vote up
function connectionTypeTuple(
    type: GraphQLObjectType | GraphQLInterfaceType
): [
    GraphQLObjectType | GraphQLInterfaceType, 
    GraphQLObjectType | GraphQLInterfaceType,
    GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType
] | undefined {
    const edges = type.getFields()["edges"];
    if (edges !== undefined) {
        const listType = 
            edges.type instanceof GraphQLNonNull ?
            edges.type.ofType : 
            edges.type;
        if (listType instanceof GraphQLList) {
            const edgeType = 
                listType.ofType instanceof GraphQLNonNull ?
                listType.ofType.ofType :
                listType.ofType;
            if (edgeType instanceof GraphQLObjectType) {
                const node = edgeType.getFields()["node"];
                if (node !== undefined) {
                    if (!(edges.type instanceof GraphQLNonNull)) {
                        waring(
                            `The type "${type.name}" is connection, its field "edges" must be not-null list`
                        );
                    }
                    if (!(listType.ofType instanceof GraphQLNonNull)) {
                        waring(
                            `The type "${type.name}" is connection, element of  its field "edges" must be not-null`
                        );
                    }
                    let nodeType: GraphQLType;
                    if (node.type instanceof GraphQLNonNull) {
                        nodeType = node.type.ofType;
                    } else {
                        waring(
                            `The type "${edgeType}" is edge, its field "node" must be non-null`
                        );
                        nodeType = node.type;
                    }
                    if (!(nodeType instanceof GraphQLObjectType) && !(nodeType instanceof GraphQLInterfaceType) && !(nodeType instanceof GraphQLUnionType)) {
                        throw new Error(
                            `The type "${edgeType}" is edge, its field "node" must be object, interface, union or their non-null wrappers`
                        );
                    }
                    const cursor = edgeType.getFields()["cursor"];
                    if (cursor === undefined) {
                        waring(
                            `The type "${edgeType}" is edge, it must defined a field named "cursor"`
                        );
                    } else {
                        const cursorType = 
                            cursor.type instanceof GraphQLNonNull ?
                            cursor.type.ofType :
                            cursor.type;
                        if (cursorType !== GraphQLString) {
                            throw new Error(
                                `The type "${edgeType}" is edge, its field "cursor" must be string`
                            );
                        }
                    }
                    return [type, edgeType, nodeType];
                }
            }
        }
    }
    return undefined;
}
Example #21
Source File: schema.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
// each key in the relationship should be included on the input object as a field to be filtered on
    inputFieldsForRelationship(relationship: MetatypeRelationship): {[key: string]: any} {
        const fields: {[key: string]: any} = {};

        relationship.keys?.forEach((relationshipKey) => {
            const propertyName = stringToValidPropertyName(relationshipKey.property_name);

            switch (relationshipKey.data_type) {
                // because we have no specification on our internal number type, we
                // must set this as a float for now
                case 'number': {
                    fields[propertyName] = {
                        type: GraphQLFloat,
                    };
                    break;
                }

                case 'boolean': {
                    fields[propertyName] = {
                        type: GraphQLBoolean,
                    };
                    break;
                }

                case 'string' || 'date' || 'file': {
                    fields[propertyName] = {
                        type: GraphQLString,
                    };
                    break;
                }

                case 'list': {
                    fields[propertyName] = {
                        type: new GraphQLList(GraphQLJSON),
                    };
                    break;
                }

                case 'enumeration': {
                    const enumMap: {[key: string]: GraphQLEnumValueConfig} = {};

                    if (relationshipKey.options) {
                        relationshipKey.options.forEach((option) => {
                            enumMap[option] = {
                                value: option,
                            };
                        });
                    }

                    fields[propertyName] = {
                        type: new GraphQLEnumType({
                            name: stringToValidPropertyName(`${relationship.name}_${relationshipKey.name}_Enum_TypeB`),
                            values: enumMap,
                        }),
                    };
                    break;
                }

                default: {
                    fields[propertyName] = {
                        type: GraphQLString,
                    };
                }
            }
        });
        return fields;
    }
Example #22
Source File: simple.ts    From graphql-sse with MIT License 5 votes vote down vote up
schemaConfig: GraphQLSchemaConfig = {
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      getValue: {
        type: new GraphQLNonNull(GraphQLString),
        resolve: () => 'value',
      },
    },
  }),
  subscription: new GraphQLObjectType({
    name: 'Subscription',
    fields: {
      greetings: {
        type: new GraphQLNonNull(GraphQLString),
        subscribe: async function* () {
          for (const hi of ['Hi', 'Bonjour', 'Hola', 'Ciao', 'Zdravo']) {
            yield { greetings: hi };
          }
        },
      },
      ping: {
        type: new GraphQLNonNull(GraphQLString),
        args: {
          key: {
            type: GraphQLString,
          },
        },
        subscribe: function (_src, args) {
          const key = args.key ? args.key : 'global';
          return {
            [Symbol.asyncIterator]() {
              return this;
            },
            async next() {
              if ((pendingPongs[key] ?? 0) > 0) {
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                pendingPongs[key]!--;
                return { value: { ping: 'pong' } };
              }
              if (
                await new Promise((resolve) => (pongListeners[key] = resolve))
              )
                return { done: true };
              return { value: { ping: 'pong' } };
            },
            async return() {
              pongListeners[key]?.(true);
              delete pongListeners[key];
              return { done: true };
            },
            async throw() {
              throw new Error('Ping no gusta');
            },
          };
        },
      },
    },
  }),
}
Example #23
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
builtInScalarMap = {
  [GraphQLString.name]: t.stringTypeAnnotation(),
  [GraphQLInt.name]: t.numberTypeAnnotation(),
  [GraphQLFloat.name]: t.numberTypeAnnotation(),
  [GraphQLBoolean.name]: t.booleanTypeAnnotation(),
  [GraphQLID.name]: t.stringTypeAnnotation(),
}
Example #24
Source File: schema.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
// each key in the metatype should be included on the input object as a field to be filtered on
    inputFieldsForMetatype(metatype: Metatype): {[key: string]: any} {
        const fields: {[key: string]: any} = {};

        metatype.keys?.forEach((metatypeKey) => {
            const propertyName = stringToValidPropertyName(metatypeKey.property_name);

            switch (metatypeKey.data_type) {
                // because we have no specification on our internal number type, we
                // must set this as a float for now
                case 'number': {
                    fields[propertyName] = {
                        type: GraphQLFloat,
                    };
                    break;
                }

                case 'boolean': {
                    fields[propertyName] = {
                        type: GraphQLBoolean,
                    };
                    break;
                }

                case 'string' || 'date' || 'file': {
                    fields[propertyName] = {
                        type: GraphQLString,
                    };
                    break;
                }

                case 'list': {
                    fields[propertyName] = {
                        type: new GraphQLList(GraphQLJSON),
                    };
                    break;
                }

                case 'enumeration': {
                    const enumMap: {[key: string]: GraphQLEnumValueConfig} = {};

                    if (metatypeKey.options) {
                        metatypeKey.options.forEach((option) => {
                            enumMap[option] = {
                                value: option,
                            };
                        });
                    }

                    // we have to include a UUID here so that we can insure a uniquely named type
                    fields[propertyName] = {
                        type: new GraphQLEnumType({
                            name: stringToValidPropertyName(`${metatype.name}_${metatypeKey.name}_Enum_Type_B`),
                            values: enumMap,
                        }),
                    };
                    break;
                }

                default: {
                    fields[propertyName] = {
                        type: GraphQLString,
                    };
                }
            }
        });

        return fields;
    }
Example #25
Source File: week.ts    From peterportal-public-api with MIT License 5 votes vote down vote up
weekType: GraphQLObjectType = new GraphQLObjectType({
    name: 'Week',
    fields: () => ({
      week: { type: GraphQLInt, description: "School week between 1-10" },
      quarter: { type: GraphQLString, description: "Quarter and year" },
      display: { type: GraphQLString, description: "Displays the week and quarter formatted" }
    })
})
Example #26
Source File: custom-type-resolver.ts    From graphql-mesh with MIT License 5 votes vote down vote up
normalizedString = GraphQLString;
Example #27
Source File: schema.ts    From apollo-server-vercel with MIT License 5 votes vote down vote up
queryType = new GraphQLObjectType({
  name: `QueryType`,
  fields: {
    testString: {
      type: GraphQLString,
      resolve(): string {
        return `it works`;
      }
    },
    testPerson: {
      type: personType,
      resolve(): { firstName: string; lastName: string } {
        return { firstName: `Jane`, lastName: `Doe` };
      }
    },
    testStringWithDelay: {
      type: GraphQLString,
      args: {
        delay: { type: new GraphQLNonNull(GraphQLInt) }
      },
      async resolve(_, args): Promise<string> {
        return new Promise((resolve) => {
          setTimeout(() => resolve(`it works`), args.delay);
        });
      }
    },
    testContext: {
      type: GraphQLString,
      resolve(_parent, _args, context): string {
        if (context.otherField) {
          return `unexpected`;
        }
        context.otherField = true;
        return context.testField;
      }
    },
    testRootValue: {
      type: GraphQLString,
      resolve(rootValue): typeof rootValue {
        return rootValue;
      }
    },
    testArgument: {
      type: GraphQLString,
      args: { echo: { type: GraphQLString } },
      resolve(_, { echo }): string {
        return `hello ${String(echo)}`;
      }
    },
    testError: {
      type: GraphQLString,
      resolve(): void {
        throw new Error(`Secret error message`);
      }
    }
  }
})
Example #28
Source File: custom-type-resolver.ts    From graphql-mesh with MIT License 5 votes vote down vote up
QName = GraphQLString;
Example #29
Source File: getBody.test.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
describe('getBody', () => {
  const arg: GraphQLArgument = {
    name: 'id',
    type: GraphQLID,
  };
  const blogArticle = new GraphQLObjectType({
    name: 'BlogArticle',
    fields: {
      id: { type: GraphQLID },
      content: { type: GraphQLString },
    },
  });

  const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
      name: 'Query',
      fields: {
        article: {
          args: { id: { type: GraphQLID } },
          type: blogArticle,
        },
      },
    }),
  });
  const mockFields = {
    filed1: 'field1',
    field2: 'field2',
  };

  beforeEach(() => {
    getFields.mockReturnValue(mockFields);
  });

  it('should return a list of arguments', () => {
    const query = schema.getQueryType().getFields().article;
    expect(getBody(query, schema, maxDepth, { useExternalFragmentForS3Object: true })).toEqual({
      args: [{ name: 'id', value: '$id' }],
      ...mockFields,
    });
    expect(getFields).toHaveBeenCalledWith(query, schema, maxDepth, { useExternalFragmentForS3Object: true });
  });
});