编辑:我相信现在可以使用新的 graphql-tools 3.0!
https://dev-blog.apollodata.com/the-next-generation-of-schema-stitching-2716b3b259c0
原答案:
这是我想出的解决方案(hack?),但可能有更好的方法:
- 使用
introspectSchema 和makeRemoteExecutableSchema 获取远程架构
- 使用
printSchema 获取架构类型定义
- 将 printSchema 收到的根 typedef
Query 和 Mutation 重命名为其他名称,例如GitHubQuery 和 GitHubMutation
- 使用类型为
GitHubQuery 的github 字段创建根查询typedef
- 创建一个
github 解析器,它使用execute 方法在远程github 架构中运行GitHubQuery
源代码: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()