What is graphql-tools?
The graphql-tools package is a set of utilities that help in the development of GraphQL schemas and resolvers in JavaScript. It provides tools for schema stitching, schema delegation, and schema transformation, among other functionalities.
What are graphql-tools's main functionalities?
Schema Stitching
Schema stitching allows you to combine multiple GraphQL schemas into a single schema. This is useful for modularizing your GraphQL API and for integrating multiple services.
const { makeExecutableSchema, mergeSchemas } = require('graphql-tools');
const schemaA = makeExecutableSchema({ typeDefs: `type Query { hello: String }`, resolvers: { Query: { hello: () => 'Hello from schema A' } } });
const schemaB = makeExecutableSchema({ typeDefs: `type Query { world: String }`, resolvers: { Query: { world: () => 'World from schema B' } } });
const mergedSchema = mergeSchemas({ schemas: [schemaA, schemaB] });
Schema Delegation
Schema delegation allows you to forward a query from one schema to another. This is useful for creating a unified API that delegates parts of the query to different underlying services.
const { delegateToSchema } = require('graphql-tools');
const schemaA = makeExecutableSchema({ typeDefs: `type Query { hello: String }`, resolvers: { Query: { hello: () => 'Hello from schema A' } } });
const resolvers = {
Query: {
helloFromA: (parent, args, context, info) => delegateToSchema({ schema: schemaA, operation: 'query', fieldName: 'hello', context, info })
}
};
Schema Transformation
Schema transformation allows you to modify an existing schema. This can include renaming types, adding or removing fields, and other modifications. This is useful for adapting third-party schemas to fit your needs.
const { transformSchema, RenameTypes } = require('graphql-tools');
const schema = makeExecutableSchema({ typeDefs: `type Query { hello: String }`, resolvers: { Query: { hello: () => 'Hello' } } });
const transformedSchema = transformSchema(schema, [new RenameTypes(name => `New_${name}`)]);
Other packages similar to graphql-tools
apollo-server
Apollo Server is a community-maintained open-source GraphQL server that works with any GraphQL schema built with graphql-tools. It provides an easy way to set up a GraphQL server with features like schema stitching, schema delegation, and more. Compared to graphql-tools, Apollo Server is more focused on providing a complete server setup, including integrations with various data sources and middleware.
graphql-compose
graphql-compose is a toolkit for generating complex GraphQL schemas in an easier and more readable way. It provides a set of utilities for schema creation, schema stitching, and schema transformation. Compared to graphql-tools, graphql-compose offers a more composable and functional approach to building GraphQL schemas.