mxcd
mxcd

Reputation: 2424

GraphQL variable combination validation

Imagine the following (simplified) GraphQL schema:

type User {
  username: String
  email: String
}

type Query {
  user(username: String, email: String): User
}

If I would only want to allow querying user by giving a username, I would of course change it to user(username: String!), making the username required using the exclamation mark. Same thing vice versa with the email.

Is it possible though to have a GraphQL native solution where I validate for the existence of only either one (logical XOR) or at least one (logical OR) of the two input parameters?
Of course I could do it in the query resolver manually, but a @constraint directive like it is being used in Apollo GraphQL spreading across variables would be nice.

Upvotes: 0

Views: 602

Answers (1)

xadm
xadm

Reputation: 8418

Directly ... not possible:

  • check fields existence [within args] on resolver;
  • use @constraint to check each field shape;

Indirectly:

  • you can try to use union of input types:

.

type UserNameInput {
  username: String!
}
type UserEmailInput {
  email: String!
}
type UserInput = UserNameInput | UserEmailInput

type Query {
  user(input: UserInput): User
}

Upvotes: 1

Related Questions