Kevin
Kevin

Reputation: 2802

How to require propertyA OR propertyB in a GraphQL Schema

In the type definition below, is there a way to require name or model, instead of name and model?

type Starship {
  id: ID!
  name: String!
  model: String!
  length(unit: LengthUnit = METER): Float
}

I may have name or model due to some legacy data limitations. I would rather enforce this at the GraphQL validation layer, rather than in code.

EDIT: There is some good discussion about adding validation to the graphQL spec, which you can read here: https://github.com/graphql/graphql-js/issues/361

There are also a couple of libraries to extend validation:

https://github.com/xpepermint/graphql-type-factory

https://github.com/stephenhandley/graphql-validated-types

I'm going to stick with validating the types in code, at least until they add better support.

Upvotes: 1

Views: 126

Answers (2)

Ken Chan
Ken Chan

Reputation: 90447

You could try to use union to represent name or model concept . As union only works with object type now , that means you have also model name and model as object type first.

Code wise the schema looks like :

type Name {
  value : String!
}

type Model {
  value : String!
}

union NameOrModel = Name | Model

type Starship {
  id: ID!
  nameOrModel : NameOrModel!
  length(unit: LengthUnit = METER): Float
}

It is very ugly IMO as it introduces many unnecessary noise and complexity to the schema .So I would prefer to stick with your original schema and do that check manually in the backend.

Upvotes: 2

Daniel Rearden
Daniel Rearden

Reputation: 84687

From the spec:

By default, all types in GraphQL are nullable; the null value is a valid response for all of the above types. To declare a type that disallows null, the GraphQL Non‐Null type can be used. This type wraps an underlying type, and this type acts identically to that wrapped type, with the exception that null is not a valid response for the wrapping type. A trailing exclamation mark is used to denote a field that uses a Non‐Null type like this: name: String!.

An individual field may be nullable or non-nullable. Non-null validation happens at the field level, independent of other fields. So there is no mechanism for validating whether some combination of fields are or are not null.

Upvotes: 1

Related Questions