Graphql - How to perform where clause

Damien Gallagher picture Damien Gallagher · Feb 11, 2018 · Viewed 27.4k times · Source

I am new to graphql and I am struggling with a query. I want to return a user by their email address

I have a type defined call V1User and it has the following fields id, email, password, role

What needs to change in this query to return a user based on email?

    query GetAllV1User {
  viewer {
     allV1Users{
      edges {
        node {
          id
          email
          role
          createdAt
          modifiedAt
        }
      }
    }
  }
}

I tried this query

    query getV1UserQuery($email: String!) {
  getV1User(email: $email) {
    id
    email
  }
}

With these params

{"email": "[email protected]"}

But get the following errors

    {
  "errors": [
    {
      "message": "Unknown argument \"email\" on field \"getV1User\" of type \"Query\".",
      "locations": [
        {
          "line": 2,
          "column": 13
        }
      ],
      "name": "GraphQLError"
    },
    {
      "message": "Field \"getV1User\" argument \"id\" of type \"ID!\" is required but not provided.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "name": "GraphQLError"
    }
  ]
}

My Schema is as follows

Name        Type        Constraints 
id          ID          NonNull Unique  
modifiedAt  DateTime    NonNull 
createdAt   DateTime    NonNull 
role        String      NonNull 
password    String      NonNull 
email       String      NonNull Unique Indexed  

Thanks

Hi

This query solved my issue

query getUserForEmailAddressAndPassword($where: V1UserWhereArgs) {
  viewer {
    allV1Users(where: $where) {
      edges {
        node {
          email
          id
          createdAt
          password
          modifiedAt
          role
        }        
      }
    }
  }
}

Along with these query variables

{"where": {"email": {"eq" : "[email protected]"}, "password": {"eq":"te2st"}}}

Answer

Aaron Dsouza picture Aaron Dsouza · May 23, 2019

I wouldn't recommend using the string "where" in your filter clause. Don't try to emulate SQL. What are you trying to filter using the where clause. If it's an email address then the query in your schema should contain user as the field and email as a parameter to that field. So the first example that you sent is the right way to do it. Also, avoid declaring queries using verbs like getUsers or getUser. The schema should just declare the query using nouns

Query
{
   Users(email:String):[User!]
}

type User 
{
    id
    email
    createdAt
    otherStuff
}