[英]Graphql - creating a schema from a generated JSON file
我正在尝试创建一个可在我的graphql Yoga服务器上使用的自定义graphql模式。 graphql Yoga服务器只是另一个graphql API的代理,我已经设法从该API检索JSON
格式的模式。 以下是该架构的外观预览:
{
"data": {
"__schema": {
"queryType": {
"name": "Query"
},
"mutationType": null,
"subscriptionType": null,
"types": [
{
"kind": "OBJECT",
"name": "Core",
"description": null,
"fields": [
{
"name": "_meta",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Meta",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "_linkType",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
现在,我想采用此生成的JSON模式,并使用它来创建要在我的graphql Yoga服务器中使用的graphql模式。 我相信正确的方法是使用来自graphql的new GraphQLSchema
方法以及根查询。 这是我的代码尝试这样做:
schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: schema.data.__schema
})
});
上面的代码给我以下错误:
错误:Query.mutationType字段配置必须是一个对象
不确定是哪里出了问题,还是不是从生成的JSON创建graphql模式的正确方法?
您拥有的JSON是自省查询的结果。 不幸的是,自省将不允许您复制远程模式。 这是因为尽管它确实标识了模式中存在哪些字段,但它并没有告诉您有关如何执行它们的任何信息。 例如,根据您发布的摘录,我们知道远程服务器公开了一个_meta
查询,该查询返回一个Meta
类型-但是我们不知道要运行什么代码来解析该查询返回的值。
从技术上讲,可以将内省查询的结果从graphql/utilities
模块传递到buildClientSchema
。 但是,该架构将无法执行,因为文档指出:
给定客户端运行自省查询的结果,创建并返回一个GraphQLSchema实例,该实例随后可与所有GraphQL.js工具一起使用,但不能用于执行查询,因为自省不代表“解析器”,“解析” ”或“序列化”功能或任何其他服务器内部机制。
如果你想创建一个代理到另一个端点GraphQL,最简单的方法是使用makeRemoteExecutableSchema
从graphql-tools
。
这是基于docs的示例:
import { HttpLink } from 'apollo-link-http';
import fetch from 'node-fetch';
const link = new HttpLink({ uri: 'http://your-endpoint-url/graphql', fetch });
async function getRemoteSchema () {
const schema = await introspectSchema(link);
return makeRemoteExecutableSchema({
schema,
link,
});
}
生成的模式是一个GraphQLSchema
对象,可以像通常一样使用:
import { GraphQLServer } from 'graphql-yoga'
async function startServer () {
const schema = await introspectSchema(link);
const executableSchema = makeRemoteExecutableSchema({
schema,
link,
});
const server = new GraphQLServer({ schema: executableSchema })
server.start()
}
startServer()
如果您不仅想代理现有端点,而且还想添加到现有端点, graphql-tools
还允许您将模式缝合在一起 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.