我们如何递归地反思GraphQL模式?
如果客户不知道模式,并且希望内省并理解GraphQL API,那么GraphQL可能无法支持递归内省。关于我的观点,请参见以下示例 首先,以下是我的高级模式定义:我们如何递归地反思GraphQL模式?,graphql,graphql-js,Graphql,Graphql Js,如果客户不知道模式,并且希望内省并理解GraphQL API,那么GraphQL可能无法支持递归内省。关于我的观点,请参见以下示例 首先,以下是我的高级模式定义: // schema.js ... ... const AuthorType = new GraphQLObjectType({ name: "Author", description: "This represent an author", fields: () => ({ id: {type: n
// schema.js
...
...
const AuthorType = new GraphQLObjectType({
name: "Author",
description: "This represent an author",
fields: () => ({
id: {type: new GraphQLNonNull(GraphQLString)},
name: {type: new GraphQLNonNull(GraphQLString)},
twitterHandle: {type: GraphQLString}
})
});
const PostType = new GraphQLObjectType({
name: "Post",
description: "This represent a Post",
fields: () => ({
id: {type: new GraphQLNonNull(GraphQLString)},
title: {type: new GraphQLNonNull(GraphQLString)},
body: {type: GraphQLString},
author: {
type: AuthorType,
resolve: function(post) {
return _.find(Authors, a => a.id == post.author_id);
}
}
})
});
// This is the Root Query
const BlogQueryRootType = new GraphQLObjectType({
name: 'BlogAppSchema',
description: "Blog Application Schema Query Root",
fields: () => ({
authors: {
type: new GraphQLList(AuthorType),
description: "List of all Authors",
resolve: function() {
return Authors
}
},
posts: {
type: new GraphQLList(PostType),
description: "List of all Posts",
resolve: function() {
return Posts
}
}
})
});
当有人使用以下查询子句查询架构时:
{
__type(name: "BlogAppSchema") {
name
fields {
name
description
type {
name
}
}
}
}
她得到以下结果:
{
"data": {
"__type": {
"name": "BlogAppSchema",
"fields": [
{
"name": "authors",
"description": "List of all Authors",
"type": {
"name": null
}
},
{
"name": "posts",
"description": "List of all Posts",
"type": {
"name": null
}
}
]
}
}
}
阅读源代码,我们知道作者是AuthorType的列表。但是,没有访问源代码的用户如何从上面得到的结果中进一步反省“authors”字段(这里的type字段显示为“null”)?她似乎无法从上述结果中知道
作者
是作者
的列表。有没有办法让她进一步反省?由于您的AuthorType
用GraphQList包装器包装,因此name
字段返回空值。这意味着该字段返回的是关于包装器的信息,而不是底层类型的信息。要获取该类型,您必须修改您的请求:
{
__type(name: "BlogAppSchema") {
name
fields {
name
description
type {
name
kind # this will show NON_NULL, LIST, SCALAR or OBJECT
ofType { # if NON_NULL or LIST what is it a non-null or list *of*
name
kind
# other fields, like "fields" which will be populated for an OBJECT
}
}
}
}
}
如果使用多个包装器(即[Author]!或[Author!]),则需要“深入”并请求嵌套的类型字段:
{
__type(name: "BlogAppSchema") {
name
fields {
name
description
type {
name
kind
ofType {
name
kind
ofType {
name
kind
ofType {
name
kind
ofType {
name
kind
}
}
}
}
}
}
}
}
如果种类
是对象
,则其字段
字段将被适当填充。然后,您可以请求每个字段的详细信息,如上所述。当然,如果有任何对象从这些字段返回,则必须指定要从这些字段中获取的信息
你可以阅读更多关于内省的内容
内省可能非常混乱。如果您需要GraphQL端点的使用者探索模式的方法,GraphiQL是一种更加用户友好的方法。还有一些方法可以动态生成文档()