如何在"GraphQL模式语言"中向字段添加描述

der*_*ery 51 javascript graphql apollo-server

我有一个graphql架构,其片段如下所示:

type User {
    username: String!
    password: String!
}
Run Code Online (Sandbox Code Playgroud)

在graphiql中,有一个描述字段,但它总是说"自我描述".如何向架构添加描述?

dav*_*aha 99

如果您使用的是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!
}
Run Code Online (Sandbox Code Playgroud)

在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!

}
Run Code Online (Sandbox Code Playgroud)

  • 这不再是默认值,请参阅:https://github.com/graphql/graphql-js/blob/master/src/utilities/extendSchema.js#L47 - 应该是一个字符串文字,如"我的描述" (3认同)

Jos*_*ack 9

这是一个很好的问题!实际上graphql世界上有着伟大的历史.

graphql-jsrepo 上有多个问题,讨论和Pull请求试图讨论可能的语法,因为这是很多社区成员认为需要的东西.感谢Lee Byron和这个Pull Request,我们实际上可以使用传统的注释为模式语言添加描述.

例如,

// 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!
}
`);
Run Code Online (Sandbox Code Playgroud)

而且,如果我们使用graphql的比较新0.7.0,则评论实际上会转换为字段或类型的描述.我们可以通过在我们的模式上运行内省查询来验证这一点:

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

graphql(schema, query)
  .then((result) => console.log(result));
Run Code Online (Sandbox Code Playgroud)

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

{
  "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"
            }
          ]
        },
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

并向我们​​表明,#评论已被纳入我们提供的字段/评论的描述中.

希望有所帮助!


Fab*_*ian 7

如果你正在使用Java实现....

对于graphql-java版本7.0(撰写本文时的最新版本)和模式第一种方法,您可以在字段,类型或参数上方使用注释.

字符串文字不是有效的语法为7.0版本.