GraphQL query and check the returned data

2019-08-02 21:37发布

问题:

I would like to have a query containing a check, for example when querying users, only users that have a non-null email are wanted. How could I add such check? Thanks!

users {
  id,
  username,
  email
}

回答1:

GraphQL fields can have arguments. So you could pass an argument to your users field, named onlyNonNullEmail: boolean:

type Query {
  users(onlyNonNullEmail: Boolean) {
    ...
  }
}

Then, inside your resolve function:

users: (_, args, context, ast) => {
  const { onlyNonNullEmail } = args;

  // If onlyNonNullEmail is true, return only users with a non-null email
  // Else proceed as usual
}