如何在另一个查询字段中包装远程模式?

Bru*_*mos 2 apollo graphql

阿波罗graphql-tools现在有Schema Stitching,这很棒.我想合并多个端点以生成类似于GraphQL Hub的模式,如下所示:

query { github: { ... } # GitHub Schema twitter: { ... } # Twitter Schema myOwnGraphqlSchema: { ... } }

如何做到这一点的最佳方法是什么?

GitHub问题:https://github.com/apollographql/graphql-tools/issues/439

在这里进行测试:https://launchpad.graphql.com/3xlrn31pv

谢谢.

Bru*_*mos 6

编辑:我相信现在可以使用新的graphql-tools 3.0了!

https://dev-blog.apollodata.com/the-next-generation-of-schema-stitching-2716b3b259c0


原始答案:

这是一个解决方案(黑客?)我提出了,但可能有更好的方法来做到这一点:

  1. 使用introspectSchema和获取远程模式makeRemoteExecutableSchema
  2. 使用获取架构类型defs printSchema
  3. 将root typedef重命名为printSchema Query并将其Mutation接收到其他内容,例如GitHubQueryGitHubMutation
  4. 使用github具有类型的字段创建根查询typedefGitHubQuery
  5. 创建一个github使用该execute方法GitHubQuery在远程github模式中运行的解析器

源代码:https://launchpad.graphql.com/3xlrn31pv

import 'apollo-link'
import fetch from 'node-fetch'
import {
  introspectSchema,
  makeExecutableSchema,
  makeRemoteExecutableSchema,
} from 'graphql-tools'
import { HttpLink } from 'apollo-link-http'
import { execute, printSchema } from 'graphql'

const link = new HttpLink({ uri: 'http://api.githunt.com/graphql', fetch })

async function getGithubRemoteSchema() {
  return makeRemoteExecutableSchema({
    schema: await introspectSchema(link),
    link,
  })
}

async function makeSchema() {
  const githubSchema = await getGithubRemoteSchema()
  const githubTypeDefs = printSchema(githubSchema)

  const typeDefs = `
        ${githubTypeDefs // ugly hack #1
      .replace('type Query', 'type GitHubQuery')
      .replace('type Mutation', 'type GitHubMutation')}

    type Query {
      github: GitHubQuery
    }

    type Mutation {
      github: GitHubMutation
    }
    `

  return makeExecutableSchema({
    typeDefs,
    resolvers: {
      Query: {
        async github(parent, args, context, info) {
          // TODO: FIX THIS

          // ugly hack #2
          // remove github root field from query
          const operation = {
            ...info.operation,
            selectionSet:
              info.operation.selectionSet.selections[0].selectionSet,
          }
          const doc = { kind: 'Document', definitions: [operation] }

          const result = await execute(
            githubSchema,
            doc,
            info.rootValue,
            context,
            info.variableValues,
            info.operation.name
          )

          return (result || {}).data
        },
      },
    },
  })
}

export const schema = makeSchema()
Run Code Online (Sandbox Code Playgroud)

  • 您能否详细说明一个示例,说明 3.0 现在如何支持此功能? (2认同)