Apollo graphql-tools
现在有模式拼接,这很棒。
我想合并多个端点以生成类似于 GraphQL Hub 的模式,像这样:
查询{
github: { ... } # GitHub 架构
twitter: { ... } # 推特模式
myOwnGraphqlSchema: { ... }
}
最好的方法是什么?
GitHub 问题:https://github.com/apollographql/graphql-tools/issues/439
在这里 fork 进行测试:https://launchpad.graphql.com/3xlrn31pv
谢谢。
最佳答案
EDIT: I believe this is now possible with the new graphql-tools 3.0!
https://dev-blog.apollodata.com/the-next-generation-of-schema-stitching-2716b3b259c0
原答案:
这是我想出的一个解决方案(hack?),但可能有更好的方法:
- 使用
introspectSchema
和makeRemoteExecutableSchema
获取远程模式 - 使用
printSchema
获取模式类型定义 - 将 printSchema 接收到的根类型定义
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()
关于graphql - 如何将远程模式包装在另一个查询字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46759547/