graphql#GraphQLSchema TypeScript Examples

The following examples show how to use graphql#GraphQLSchema. 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 graphql-eslint with MIT License 7 votes vote down vote up
export function requireGraphQLSchemaFromContext(
  ruleId: string,
  context: GraphQLESLintRuleContext
): GraphQLSchema | never {
  const { schema } = context.parserServices;
  if (!schema) {
    throw new Error(
      `Rule \`${ruleId}\` requires \`parserOptions.schema\` to be set and loaded. See https://bit.ly/graphql-eslint-schema for more info`
    );
  } else if (schema instanceof Error) {
    throw schema;
  }
  return schema;
}
Example #2
Source File: app.ts    From one-platform with MIT License 6 votes vote down vote up
export async function startApolloServer(schema: GraphQLSchema) {
  const context: ContextFunction<FastifyContext> = async ({ request }) => {
    const id = request?.headers?.['x-op-user-id'];
    const loaders = {
      user: setupUserDataLoader(config.apiGatewayURL, config.apiGatewayToken),
    };

    return { loaders, user: { id } };
  };

  const app = fastify({
    logger: true,
  });
  const server = new ApolloServer({
    schema,
    context,
    dataSources: () => {
      return {
        analyticsConfig: new AnalyticsConfig(Analytics),
        sentryAPI: new SentryAPI(config.sentryAPIURL, config.sentryAPIToken, 'rhcp', pool),
      };
    },
    formatError: (error) => ({
      message: error.message,
      locations: error.locations,
      path: error.path,
      ...error.extensions,
    }),
    plugins: [
      fastifyAppClosePlugin(app),
      ApolloServerPluginDrainHttpServer({ httpServer: app.server }),
    ],
  });

  await server.start();
  app.register(server.createHandler());
  await app.listen(config.port);
  logger.info(`? Server ready at http://localhost:${config.port}${server.graphqlPath}`);
}
Example #3
Source File: no-unused-fields.ts    From graphql-eslint with MIT License 6 votes vote down vote up
function getUsedFields(schema: GraphQLSchema, operations: SiblingOperations): UsedFields {
  // We don't want cache usedFields on test environment
  // Otherwise usedFields will be same for all tests
  if (process.env.NODE_ENV !== 'test' && usedFieldsCache) {
    return usedFieldsCache;
  }
  const usedFields: UsedFields = Object.create(null);
  const typeInfo = new TypeInfo(schema);

  const visitor = visitWithTypeInfo(typeInfo, {
    Field(node): false | void {
      const fieldDef = typeInfo.getFieldDef();
      if (!fieldDef) {
        // skip visiting this node if field is not defined in schema
        return false;
      }
      const parentTypeName = typeInfo.getParentType().name;
      const fieldName = node.name.value;

      usedFields[parentTypeName] ??= new Set();
      usedFields[parentTypeName].add(fieldName);
    },
  });

  const allDocuments = [...operations.getOperations(), ...operations.getFragments()];
  for (const { document } of allDocuments) {
    visit(document, visitor);
  }
  usedFieldsCache = usedFields;
  return usedFieldsCache;
}
Example #4
Source File: graphql.factory.ts    From nestjs-mercurius with MIT License 6 votes vote down vote up
async mergeOptions(options?: any): Promise<any> {
    if (options.federationMetadata) {
      options.buildSchemaOptions = {
        ...options.buildSchemaOptions,
        skipCheck: true,
      };
    }
    const parentOptions = (await super.mergeOptions(
      options as any,
    )) as unknown as MercuriusModuleOptions & {
      plugins: any[];
      schema: GraphQLSchema;
    };
    if (parentOptions.plugins?.length) {
      const pluginNames = parentOptions.plugins
        .map((p) => p.name)
        .filter(Boolean);
      this.logger.warn(
        `Plugins are not supported by Mercurius, ignoring: ${pluginNames.join(
          ', ',
        )}`,
      );
    }
    delete parentOptions.plugins;
    parentOptions.loaders = this.loaderExplorerService.explore();
    if (options.federationMetadata) {
      parentOptions.schema = transformFederatedSchema(parentOptions.schema);
    }

    return parentOptions;
  }
Example #5
Source File: generate-query.d.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
export declare function generateRandomMutation(schema: GraphQLSchema, config?: Configuration): {
    mutationDocument: DocumentNode;
    variableValues: {
        [varName: string]: any;
    };
    seed: number;
    typeCount: number;
    resolveCount: number;
};
Example #6
Source File: schema.ts    From apollo-server-vercel with MIT License 6 votes vote down vote up
TestSchema = new GraphQLSchema({
  query: QueryRootType,
  mutation: new GraphQLObjectType({
    name: `MutationRoot`,
    fields: {
      writeTest: {
        type: QueryRootType,
        resolve: (): {} => ({})
      }
    }
  })
})
Example #7
Source File: generate-operations.ts    From graphql-mesh with MIT License 6 votes vote down vote up
export function generateOperations(schema: GraphQLSchema, options: YamlConfig.GenerateOperationsConfig): Source[] {
  const sources: Source[] = [];
  const rootTypeMap = getRootTypeMap(schema);
  for (const [operationType, rootType] of rootTypeMap) {
    const fieldMap = rootType.getFields();
    for (const fieldName in fieldMap) {
      const operationNode = buildOperationNodeForField({
        schema,
        kind: operationType,
        field: fieldName,
        depthLimit: options.selectionSetDepth,
      });
      const defaultName = `operation_${sources.length}`;
      const virtualFileName = operationNode.name?.value || defaultName;
      const rawSDL = print(operationNode);
      const source = parseGraphQLSDL(`${virtualFileName}.graphql`, rawSDL);
      sources.push(source);
    }
  }
  return sources;
}
Example #8
Source File: get-type-info.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export function getTypeInfo(typeNode: TypeNode, schema: GraphQLSchema): TypeInfo {
  if (typeNode.kind === 'NamedType') {
    return {
      type: typeNode.name.value,
      isNullable: true,
      isList: false,
      baseType: schema.getType(typeNode.name.value),
    };
  } else if (typeNode.kind === 'NonNullType' && typeNode.type.kind === 'ListType') {
    return {
      ...getTypeInfo(typeNode.type.type, schema),
      isList: true,
      isListNullable: false,
    };
  } else if (typeNode.kind === 'NonNullType') {
    return {
      ...getTypeInfo(typeNode.type, schema),
      isNullable: false,
    };
  } else if (typeNode.kind === 'ListType') {
    return {
      ...getTypeInfo(typeNode.type, schema),
      isList: true,
      isListNullable: true,
    };
  }
  return {
    isList: false,
    isNullable: false,
    type: typeNode,
  };
}
Example #9
Source File: CommonTypesWriter.ts    From graphql-ts-client with MIT License 6 votes vote down vote up
constructor(
        schema: GraphQLSchema,
        private inheritanceInfo: InheritanceInfo,
        stream: WriteStream, 
        config: GeneratorConfig
    ) {
        super(stream, config);
        const info = new InheritanceInfo(schema);
    }
Example #10
Source File: index.test.ts    From hono with MIT License 6 votes vote down vote up
TestSchema = new GraphQLSchema({
  query: QueryRootType,
  mutation: new GraphQLObjectType({
    name: 'MutationRoot',
    fields: {
      writeTest: {
        type: QueryRootType,
        resolve: () => ({}),
      },
    },
  }),
})
Example #11
Source File: index.ts    From aloxide with Apache License 2.0 6 votes vote down vote up
graphqlSchema = new GraphQLSchema({
  types: graphqlFields.map(({ graphQLObjectType }) => graphQLObjectType),
  query: new GraphQLObjectType({
    name: 'Query',
    fields: graphqlFields
      .map(({ connectionQueryField }) => connectionQueryField)
      .reduce(
        (a, c) =>
          Object.assign(a, {
            [`query${c.name}`]: c,
          }),
        {},
      ),
  }),
})
Example #12
Source File: getTestIntrospection.ts    From ra-data-prisma with MIT License 6 votes vote down vote up
buildIntrospection = async (
  rawSchema: GraphQLSchema,
  options: CommonOptions,
) => {
  const schema = await graphql(rawSchema, getIntrospectionQuery()).then(
    ({ data: { __schema } }) => __schema,
  );
  return introspection(null, {
    ...makeIntrospectionOptions({ ...options, ...defaultOurOptions }),
    schema: schema,
  }) as IntrospectionResult;
}
Example #13
Source File: renderChainTypes.ts    From genql with MIT License 6 votes vote down vote up
renderChainTypes = (schema: GraphQLSchema, ctx: RenderContext) => {
  const typeMap = ctx.config?.sortProperties
    ? sortKeys(schema.getTypeMap())
    : schema.getTypeMap()

  for (const name in typeMap) {
    if (excludedTypes.includes(name)) continue

    const type = typeMap[name]

    // TODO handle unions
    if (isObjectType(type) || isInterfaceType(type)) {
      objectType(type, ctx, 'Promise')
      objectType(type, ctx, 'Observable')
    }
  }
}
Example #14
Source File: app.ts    From one-platform with MIT License 5 votes vote down vote up
startApolloServer = async (gqlSchema: GraphQLSchema, config: Config) => {
  const context: ContextFunction<FastifyContext> = async ({ request }) => {
    const id = request?.headers?.['x-op-user-id'];
    const loaders = {
      user: setupUserDataLoader(config.apiGatewayURL, config.apiGatewayToken),
      subscriptionStatus: setupSubscriptionStatusLoader(),
    };

    return { loaders, user: { id } };
  };

  const app = fastify({
    logger: true,
  });

  const server = new ApolloServer({
    schema: gqlSchema,
    context,
    dataSources: () => {
      return {
        namespaceDB: new NamespaceDB(Namespace),
        subscriptionDB: new SubscriptionDB(Subscription),
        specStoreDB: new SpecStoreDB(SpecStore),
      };
    },
    formatError: (error) => ({
      message: error.message,
      locations: error.locations,
      path: error.path,
      ...error.extensions,
    }),
    plugins: [
      fastifyAppClosePlugin(app),
      ApolloServerPluginDrainHttpServer({ httpServer: app.server }),
    ],
  });

  await server.start();
  app.register(server.createHandler());
  await app.listen(config.port, '0.0.0.0');
}
Example #15
Source File: converter.ts    From graphql-eslint with MIT License 5 votes vote down vote up
export function convertToESTree<T extends DocumentNode>(node: T, schema?: GraphQLSchema) {
  const typeInfo = schema ? new TypeInfo(schema) : null;

  const visitor: ASTVisitor = {
    leave(node, key, parent) {
      const leadingComments: Comment[] =
        'description' in node && node.description
          ? [
              {
                type: node.description.block ? 'Block' : 'Line',
                value: node.description.value,
              },
            ]
          : [];

      const calculatedTypeInfo: TypeInformation | Record<string, never> = typeInfo
        ? {
            argument: typeInfo.getArgument(),
            defaultValue: typeInfo.getDefaultValue(),
            directive: typeInfo.getDirective(),
            enumValue: typeInfo.getEnumValue(),
            fieldDef: typeInfo.getFieldDef(),
            inputType: typeInfo.getInputType(),
            parentInputType: typeInfo.getParentInputType(),
            parentType: typeInfo.getParentType(),
            gqlType: typeInfo.getType(),
          }
        : {};

      const rawNode = () => {
        if (parent && key !== undefined) {
          return parent[key];
        }
        return node.kind === Kind.DOCUMENT
          ? <DocumentNode>{
              ...node,
              definitions: node.definitions.map(definition =>
                (definition as unknown as GraphQLESTreeNode<DefinitionNode>).rawNode()
              ),
            }
          : node;
      };

      const commonFields: Omit<GraphQLESTreeNode<typeof node>, 'parent'> = {
        ...node,
        type: node.kind,
        loc: convertLocation(node.loc),
        range: [node.loc.start, node.loc.end],
        leadingComments,
        // Use function to prevent RangeError: Maximum call stack size exceeded
        typeInfo: () => calculatedTypeInfo as any, // Don't know if can fix error
        rawNode,
      };

      return 'type' in node
        ? {
            ...commonFields,
            gqlType: node.type,
          }
        : commonFields;
    },
  };

  return visit(node, typeInfo ? visitWithTypeInfo(typeInfo, visitor) : visitor) as GraphQLESTreeNode<T>;
}
Example #16
Source File: schema.ts    From anthem with Apache License 2.0 5 votes vote down vote up
schema: GraphQLSchema = makeExecutableSchema({
  typeDefs,
  resolvers,
})
Example #17
Source File: faderation-factory.util.ts    From nestjs-mercurius with MIT License 5 votes vote down vote up
/**
 * Inspired by https://github.com/mercurius-js/mercurius/blob/master/lib/federation.js#L231
 * Accept a GraphQLSchema to transform instead of a plain string containing a graphql schema
 * @param schema
 */
export function transformFederatedSchema(schema: GraphQLSchema) {
  // FIXME remove this dependency
  // but graphql#printSchema does not print necessary federation directives
  const { printSubgraphSchema } = loadPackage(
    '@apollo/subgraph',
    'FederationFactory',
    () => require('@apollo/subgraph'),
  );

  // Workaround for https://github.com/mercurius-js/mercurius/issues/273
  const schemaString = printSubgraphSchema(schema)
    .replace('type Query {', 'type Query @extends {')
    .replace('type Mutation {', 'type Mutation @extends {')
    .replace('type Subscription {', 'type Subscription @extends {');

  schema = extendSchema(schema, parse(FEDERATION_SCHEMA), {
    assumeValidSDL: true,
  });

  if (!schema.getType('Query')) {
    schema = new GraphQLSchema({
      ...schema.toConfig(),
      query: new GraphQLObjectType({
        name: 'Query',
        fields: {},
      }),
    });
  }

  schema = extendSchema(
    schema,
    parse(`
    extend type Query {
      _service: _Service!
    }
  `),
    {
      assumeValid: true,
    },
  );

  const query = schema.getType('Query') as GraphQLObjectType;
  const queryFields = query.getFields();

  queryFields._service = {
    ...queryFields._service,
    resolve: () => ({ sdl: schemaString }),
  };

  const entityTypes = Object.values(schema.getTypeMap()).filter(
    (type) => isObjectType(type) && typeIncludesDirective(type, 'key'),
  );

  if (entityTypes.length > 0) {
    schema = extendSchema(
      schema,
      parse(`
      union _Entity = ${entityTypes.join(' | ')}
      extend type Query {
        _entities(representations: [_Any!]!): [_Entity]!
      }
    `),
      {
        assumeValid: true,
      },
    );

    const query = schema.getType('Query') as GraphQLObjectType;
    const queryFields = query.getFields();
    queryFields._entities = {
      ...queryFields._entities,
      resolve: (_source, { representations }, context, info) => {
        return representations.map((reference) => {
          const { __typename } = reference;

          const type = info.schema.getType(__typename);
          if (!type || !isObjectType(type)) {
            throw new MER_ERR_GQL_GATEWAY_INVALID_SCHEMA(__typename);
          }

          const resolveReference = (type as any).resolveReference
            ? (type as any).resolveReference
            : function defaultResolveReference() {
                return reference;
              };

          const result = resolveReference(reference, {}, context, info);

          if (result && 'then' in result && typeof result.then === 'function') {
            return result.then((x) => addTypeNameToResult(x, __typename));
          }

          return addTypeNameToResult(result, __typename);
        });
      },
    };
  }

  return schema;
}
Example #18
Source File: index.d.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
constructor(gitHubSchema: GraphQLSchema, gitHubQueryConfig: Configuration);
Example #19
Source File: schema.ts    From apollo-server-vercel with MIT License 5 votes vote down vote up
schema = new GraphQLSchema({
  query: queryType,
  mutation: mutationType
})
Example #20
Source File: ts-artifacts.ts    From graphql-mesh with MIT License 5 votes vote down vote up
async function generateTypesForApi(options: { schema: GraphQLSchema; name: string }) {
  const baseTypes = await codegen({
    filename: options.name + '_types.ts',
    documents: [],
    config: {
      skipTypename: true,
      namingConvention: 'keep',
      enumsAsTypes: true,
      ignoreEnumValuesFromSchema: true,
    },
    schemaAst: options.schema,
    schema: undefined as any, // This is not necessary on codegen. Will be removed later
    skipDocumentsValidation: true,
    plugins: [
      {
        typescript: {},
      },
    ],
    pluginMap: {
      typescript: tsBasePlugin,
    },
  });
  const codegenHelpers = new CodegenHelpers(options.schema, {}, {});
  const namespace = pascalCase(`${options.name}Types`);
  const sdkIdentifier = pascalCase(`${options.name}Sdk`);
  const contextIdentifier = pascalCase(`${options.name}Context`);
  const queryOperationMap = buildSignatureBasedOnRootFields(codegenHelpers, options.schema.getQueryType(), namespace);
  const mutationOperationMap = buildSignatureBasedOnRootFields(
    codegenHelpers,
    options.schema.getMutationType(),
    namespace
  );
  const subscriptionsOperationMap = buildSignatureBasedOnRootFields(
    codegenHelpers,
    options.schema.getSubscriptionType(),
    namespace
  );

  const sdk = {
    identifier: sdkIdentifier,
    codeAst: `
    export namespace ${namespace} {
      ${baseTypes}
    }
    export type Query${sdkIdentifier} = {
${Object.values(queryOperationMap).join(',\n')}
};

export type Mutation${sdkIdentifier} = {
${Object.values(mutationOperationMap).join(',\n')}
};

export type Subscription${sdkIdentifier} = {
${Object.values(subscriptionsOperationMap).join(',\n')}
};`,
  };

  const context = {
    identifier: contextIdentifier,
    codeAst: `export type ${contextIdentifier} = {
      ["${options.name}"]: { Query: Query${sdkIdentifier}, Mutation: Mutation${sdkIdentifier}, Subscription: Subscription${sdkIdentifier} },
    };`,
  };

  return {
    sdk,
    context,
  };
}