2016-10-10 62 views
14

我有一个graphql架构描述添加到现场,其中一个片段是这样的:如何在“GraphQL模式语言”

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

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

+0

PS哈希您的密码的孩子! – derekdreery

回答

29

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

# 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版本,无法在模式语言中添加说明。

UPDATE:从版本v0.12.3你应该使用字符串文字

"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

这不再是默认值,请参阅:https://github.com/graphql/graphql-js/blob/master/src/utilities/extendSchema.js#L47 - 应该是一个字符串文字,例如“我的描述” ' – Casey

+0

所以字符串文字是截至2018年2月的当前默认值。 – Vincent

6

这是一个很大的问题!而且其实在graphql世界有很大的历史。

graphql-js回购协议中存在多个问题,讨论和合并请求,试图讨论可能的语法,因为这是社区中许多成员认为需要的东西。感谢Lee Byron和this 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! 
} 
`); 

而且,如果我们使用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

+0

是的,花了我一段时间才找到。 TYVM! – DJC

+0

我正在使用graphql 0.12.3,但这不适用于我。使用上面的代码,说明始终为空。 – Casey

2

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

对于7.0版本graphql-java(最新版本撰写本文时)与模式第一种方法,你可以使用上面的评论字段,类型或参数。

字符串文字而不是自版本7.0起的有效语法。