GraphQL - 仅允许输入类型的某些值

Mic*_*tor 6 ruby-on-rails graphql graphql-ruby

我正在使用[graphql][1]gem构建一个GraphQL API.

在定义输入时,例如 -

Inputs::BranchInput = GraphQL::InputObjectType.define do
  name 'BranchInput'

  argument :scope,                      types.String
end
Run Code Online (Sandbox Code Playgroud)

该参数scope实际上是一个enum字段,它将接受small或者big.如何在输入中定义此参数只接受这两个值?是否有可能在生成文档时在文档中显示此内容,以便UI开发人员也清楚这一点?

当使用Grape生成REST API时,我通常会使用values参数来定义这样的东西.

Grz*_*orz 0

您基本上有两个选择:

  1. 验证器(内置的就足够了
argument :scope,  types.String, validates: { 
  inclusion: { in: %w[small big] }
}
Run Code Online (Sandbox Code Playgroud)

这只会导致运行时检查。

  1. 枚举(首选)
class Types::ScopeEnum < Types::BaseEnum
  value "BIG", "when you need things big"
  value "SMALL", "when you need'em small"
end

argument :scope,  Types::ScopeEnum # I'm not familiat with `types.` notation so I'm not sure how to use custom enum this way. 
Run Code Online (Sandbox Code Playgroud)

这将反映在您的架构中,从而更好地向 API 用户(客户端)记录您的意图