GraphQL - Allow only certain values for Input Types
Asked Answered
I

1

7

I am using the [graphql][1] gem to build out a GraphQL API.

When defining inputs for example --

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

  argument :scope,                      types.String
end

The argument scope is actually an enum field that will accept either small or big. How can I define this in the input that this argument will only accept these two values? Is it possible to show this in the docs as well when they are generated so that the UI developers are also clear on this?

When using Grape to generate REST APIs, I would generally use to values parameter to define something like this.

Insubordinate answered 11/4, 2018 at 18:0 Comment(1)
This is a late answer, but I imagine you'd want something like an Enum, it's what we're using for similar case. github.com/rmosolgo/graphql-ruby/blob/master/lib/graphql/…Manana
C
0

You have basically two options:

  1. Validators (built-in should suffice)
argument :scope,  types.String, validates: { 
  inclusion: { in: %w[small big] }
}

This will cause a runtime check only.

  1. Enum (preferred)
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 familiar with `types.` notation so I'm not sure how to use custom enum this way. 

This would be reflected in your schema, which in turn better documents your intent to the API users (clients)

Cahn answered 1/3 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.