Query by 2 or more fields on GraphQL
We are using Slack at YLD along with missions.ai, allowing our employees to get some relevant information about them or about other people in the company. It helps to answer questions such as "How many hardware budget do I still have?" or "Is the person X on holidays?", or simply to request bussiness cards.
We are grabbing some data about the person from different data sources such as BambooHR or Slack. We decided to go with a GraphQL + Apollo solution for the API and our schema is similar to the following:
We are currently adding more missions to our list and we saw that querying
What we want is something such as the following:
Unfortunately this is not possible in GraphQL! What exactly do we want?
- query by employee email or slackId
- email or slackId are required
One possible solution is to add two different queries and resolvers:
This works and it is an explicit solution: everyone that reads this piece of code understands exaclty what it does. However, if we have 10 other fields we might want to query (e.g Github handle or Twitter handle, which are both unique values) we can end up with a messy solution that is not scalable.
Another solution we can think of is having both fields for the same resolver as follows:
In this case we miss the required (!) field filter in the query and that validation has to be done inside the resolver:
This could also be confusing if you just look at the
Query defined in the GraphQL schema. Moreover, if you have multiple parameters to filter from we would have the same issue for all of them. This solution is also confusing and not scalable.
EmployeeSearch in our query refering it as a required field (!). This way we are specifing that at least one of the fields should be used to perform the query.
This is a solution that is more declarative and clear when we look at the schema. Furthermore, it is widely used in projects like Gatsby (check GraphQLInputObjectType used in Gatsby for details). In comparison with the former solutions presented, using Input Types is more scalable but has the disadvantage of having to filter by field inside the resolver. Also, we should not forget that the resolver must give an Error if either email or slackId are not sent to query employee:
We ended up using input types and making our schema clean and meaning. In order to make it even prettier we followed open-crud specification ideas, which is used by interesting projects like Prisma or Postgraphile.
Enjoy input types!