如何在“GraphQL模式语言”中为字段添加描述

86

我有一个GraphQL模式,其中一部分如下所示:

type User {
    username: String!
    password: String!
}

在 GraphiQL 中,有一个描述字段,但它总是说“自我描述”。我该如何向模式添加描述?


6
小朋友们,请给你们的密码加上哈希值! - derekdreery
3个回答

167

如果您使用的是GraphQL.js版本0.7.0或更高版本,则可以在要描述的字段、类型或参数之前直接添加注释。例如:

# A type that describes the user
type User {
     # The user's username, should be typed in the login field.
     username: String!
     # The user's password.
     password: String!
}

在0.7.0版本以下,不可能在模式语言中添加描述。

更新:从v0.12.3版本开始,您应该使用字符串字面量

"""
A type that describes the user. Its description might not 
fit within the bounds of 80 width and so you want MULTILINE
"""
type User {
     "The user's username, should be typed in the login field."
     username: String!
     "The user's password."
     password: String!

}

6
不再是默认设置,请参见:https://github.com/graphql/graphql-js/blob/master/src/utilities/extendSchema.js#L47-- 应该是一个字符串字面量,例如“我的描述”。 - Casey
1
所以字符串字面量是截至2018年2月的当前默认设置。 - Vincent Cantin
相关规范部分:https://graphql.github.io/graphql-spec/June2018/#sec-Descriptions - Sampo
1
如果有人想知道如何在TypeGraphQL中实现此操作,只需在装饰器选项中使用“description”属性。例如:@ObjectType({description:'Here'})。对于@Field({description:...},@Arg和@Query也是同样的方法。 - user10706046

18

这是一个很棒的问题!实际上,在graphql世界中有着悠久的历史。

graphql-js存储库上曾经有过多个问题、讨论和拉取请求,试图讨论可能的语法,因为这是社区许多成员感到需要的东西。多亏了李·拜伦(Lee Byron)和这个拉取请求,我们现在可以通过传统注释向模式语言添加描述。

例如,

// Grab some helpers from the `graphql` project
const { buildSchema, graphql } = require('graphql');

// Build up our initial schema
const schema = buildSchema(`
schema {
  query: Query
}

# The Root Query type
type Query {
  user: User
}

# This is a User in our project
type User {
  # This is a user's name
  name: String!

  # This is a user's password
  password: String!
}
`);

如果我们使用的graphql版本新于0.7.0,那么注释实际上会变成字段或类型的描述。我们可以通过在模式上运行内省查询来验证这一点:

const query = `
{
  __schema {
    types {
        name
        description,
        fields {
            name
            description
        }
    }
  }
}
`;

graphql(schema, query)
  .then((result) => console.log(result));

这将给我们一个看起来像这样的结果:

{
  "data": {
    "__schema": {
      "types": [
        {
          "name": "User",
          "description": "This is a User in our project",
          "fields": [
            {
              "name": "name",
              "description": "This is a user's name"
            },
            {
              "name": "password",
              "description": "This is a user's password"
            }
          ]
        },
      ]
    }
  }
}

它向我们展示,# 注释被作为我们放在对应字段/注释上的描述而纳入了其中。

希望这有所帮助!


1
非常有帮助,谢谢 - 我花了很长时间搜索答案,并且在处理许多旧问题时感到困难 - 当答案如此简单时! :) - derekdreery
是的,我也花了一些时间才找到。非常感谢! - DJC
我正在使用graphql 0.12.3,但这对我不起作用。使用上面的代码,描述始终为空。 - Casey

8

如果您使用的是Java实现....

对于graphql-java版本7.0(截至本篇撰写时的最新版本)采用模式优先方法,您可以在字段、类型或参数上方使用注释.

字符串字面量不是7.0版本的有效语法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接