graphql-transform-schema

Transform, filter & alias resolvers of a GraphQL schema

Stars
84
Committers
3

graphql-transform-schema has been deprecated in favor of schema transforms as part of graphql-tools

graphql-transform-schema npm version Greenkeeper badge

Transform, filter & alias resolvers of a GraphQL schema

Install

yarn add graphql-transform-schema

Usage

By default transformSchema passes through all queries/mutations. (Open Demo)

import { transformSchema } from 'graphql-transform-schema'

// needed for remote schemas
import { createApolloFetch } from 'apollo-fetch'
import { makeRemoteExecutableSchema } from 'graphql-tools'

const schema = await makeRemoteExecutableSchema(createApolloFetch({
  uri: 'https://api.graph.cool/simple/v1/swapi',
}))

// hide every query/mutation except the `Starship` and `allStarships` query
const transformedSchema = transformSchema(schema, {
  '*': false,
  Starship: true,
  allStarships: true,
})

const transformedSchema = transformSchema(schema, {
  Query: {
    '*': false,
    Starship: true,
    allStarships: true,
  },
  Mutation: {
  
  },
  Starship: {
    '*': false,
    id: true,
  },
})

API

interface Rules {
  [fieldName: string]: boolean | Function
}

function transformSchema(schema: GraphQLSchema, rules: Rules): GraphQLSchema

Examples

Remove all createX and deleteX mutations

const transformedSchema = transformSchema(schema, {
  Mutation: {
    'create*': false,
    'delete*': false
  }
})

Overwrite resolved data

const typeDefs = `
  type Query {
    hello: String!
  }

  type Mutation {
    alexaHello(name: String!): String!
  }
`
const resolvers = {
  Query: {
    hello: () => 'Hello world',
  },
  Mutation: {
    alexaHello: (_, { name }) => `Alexa: Hello world, ${name}`,
  },
}
const schema = makeExecutableSchema({ typeDefs, resolvers })

const transformedSchema = transformSchema(schema, {
  alexaHello: ({ args, resolve }) => resolve(args).replace('Bob', 'Alice'),
})

Overwrite arguments

const typeDefs = `
  type Query {
    hello: String!
  }

  type Mutation {
    alexaHello(name: String!): String!
  }
`
const resolvers = {
  Query: {
    hello: () => 'Hello world',
  },
  Mutation: {
    alexaHello: (_, { name }) => `Alexa: Hello world, ${name}`,
  },
}
const schema = makeExecutableSchema({ typeDefs, resolvers })

const transformedSchema = transformSchema(schema, {
  alexaHello: ({ args, resolve }) => resolve({ name: 'John' }),
})

Next steps

  • Alias/rename types and fields
  • Transform field arguments
  • Compose new queries/mutations out of existing queries/mutations

Help & Community Slack Status

Join our Slack community if you run into issues or have questions. We love talking to you!

Badges
Extracted from project README
npm version Greenkeeper badge Slack Status
Related Projects