graphql-tools

repository·master·Indexed 26 days ago

https://github.com/ardatan/graphql-tools

A toolkit for building, managing, and composing GraphQL schemas. It provides utilities for schema generation, mocking, and schema stitching, along with specialized packages for document optimization (@graphql-tools/optimize), execution (@graphql-tools/executor), and build-time preprocessing via Jest (@graphql-tools/jest-transform) and Webpack (@graphql-tools/webpack-loader).

Tokens
56.8K
Snippets
124
Records
330
Agent score
90%

What's inside graphql-tools

  1. Introduction to GraphQL Tools

    master

    GraphQL Tools is a collection of npm packages (prefixed with @graphql-tools/) designed to help you build JavaScript GraphQL schemas and resolvers using a GraphQL-first development workflow.

    Key characteristics:

    • Versatility: While optimized for building servers, the tools can also be used in the browser (e.g., for mocking backends during development or testing).
    • Compatibility: The tools work with any standard GraphQL-JS schema, meaning you can use individual tools even if you do not follow the recommended project structure.
    • Ecosystem: It provides a set of utilities to build schemas in a concise and powerful way.
  2. Create a GraphQL schema with graphql-tools

    master

    The graphql-tools package provides several ways to build and manage GraphQL schemas:

    1. Generate a schema: Use the GraphQL schema language to create a schema with full support for resolvers, interfaces, unions, and custom scalars. The resulting schema is compatible with GraphQL.js.
    2. Mock a GraphQL API: Implement fine-grained, per-type mocking for your API.
    3. Stitch schemas: Automatically combine multiple existing schemas into a single, larger API.
  3. Use schema directives to transform your schema

    master

    You can apply custom directives to a schema generated by makeExecutableSchema by passing the schema through a directive transformer function. This allows you to modify the structure or behavior of types, fields, and arguments without changing the underlying SDL.

    import { renameDirective } from 'fake-rename-directive-package'
    import { makeExecutableSchema } from '@graphql-tools/schema'
    
    const typeDefs = /* GraphQL */ `
      type Person @rename(to: "Human") {
        name: String!
        currentDateMinusDateOfBirth: Int @rename(to: "age")
      }
    `
    
    let schema = makeExecutableSchema({
      typeDefs
    })
    
    schema = renameDirective('rename')(schema)
  4. Mock a schema using Introspection

    master

    If your schema is defined in a language other than JavaScript (e.g., Go, Ruby, Python), you can mock it by using an introspection JSON result. Use buildClientSchema from the graphql package to convert the introspection result into a GraphQLSchema object, then pass it to addMocksToSchema.

    import { buildClientSchema } from 'graphql'
    import * as introspectionResult from 'schema.json'
    import { addMocksToSchema } from '@graphql-tools/mock'
    
    const schema = buildClientSchema(introspectionResult)
    const schemaWithMocks = addMocksToSchema({ schema })
  5. Mock a GraphQL schema with default logic

    master

    You can mock a GraphQL schema with a single line of code using addMocksToSchema. By default, the mocking logic inspects your schema and returns appropriate primitive values (e.g., a string for a String type, a number for a Number type) to ensure the result matches the expected shape.

    Note: If your schema contains custom scalar types, you must define the __serialize, __parseValue, and __parseLiteral functions and pass them as the second argument to makeExecutableSchema.

    import { graphql } from 'graphql'
    import { addMocksToSchema } from '@graphql-tools/mock'
    import { makeExecutableSchema } from '@graphql-tools/schema'
    
    // Fill this in with the schema string
    const schemaString = `...` 
    
    // Make a GraphQL schema with no resolvers
    const schema = makeExecutableSchema({ typeDefs: schemaString })
    
    // Create a new schema with mocks
    const schemaWithMocks = addMocksToSchema({ schema })
    
    const query = /* GraphQL */ `
      query tasksForUser {
        user(id: 6) {
          id
          name
        }
      }
    `
    
    graphql({
      schema: schemaWithMocks,
      source: query
    }).then(result => console.log('Got result', result))
  6. Migrate from graphql-import to @graphql-tools/load

    master

    The graphql-import package has been replaced by the @graphql-tools/load and @graphql-tools/graphql-file-loader packages within the GraphQL Tools monorepo. To support the #import syntax in .graphql files, you must now use loadSchemaSync (or the asynchronous loadSchema) combined with a GraphQLFileLoader instance passed into the loaders option.

    import { join } from 'node:path'
    import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader'
    import { loadSchemaSync } from '@graphql-tools/load'
    import { addResolversToSchema } from '@graphql-tools/schema'
    
    const schema = loadSchemaSync(join(__dirname, 'schema.graphql'), {
      loaders: [new GraphQLFileLoader()]
    })
    
    const resolvers = {
      Query: {
        // ...
      }
    }
    
    const schemaWithResolvers = addResolversToSchema({ schema, resolvers })
  7. Add descriptions and deprecations to the schema

    master

    You can add documentation to your schema using docstrings (triple quotes """) for types, fields, and arguments. This is supported by tools like GraphiQL. You can also deprecate fields using the @deprecated directive.

    """
    Description for the type
    """
    type MyObjectType {
      """
      Description for field
      Supports multi-line description
      """
      myField: String!
    
      otherField(
        """
        Description for argument
        """
        arg: Int
      ) @deprecated(reason: "Use otherField instead.")
    }