How to search string values in GraphQL

Solution 1:

The short answer is: you don't.

The longer answer is that you have to write that code yourself. GraphQL isn't a database query language like SQL, it's an application query language. What that means is that GraphQL won't let you write arbitrary queries out of the box. It will only support the types of queries defined in your GraphQL schema.

If you want to be able to write a query that contains like, you have to

a) declare that in the schema, and b) write a resolve function that fetches the data

For example, you could have this schema:

type Query {
  users(firstName: String!): [User]
}

type User {
  firstName: String
  lastName: String
}

You would have to define the following resolve function for the users field:

{
  Query: {
    users(root, args){
      return sql.raw('SELECT * FROM `users` WHERE `firstName` LIKE ?', args.firstName);
    }
  }
}

And finally write this query to get a list of firstName and lastName of all the users that match your search criteria:

{
  users(firstName: 'jason%'){
    firstName
    lastName
  }
} 

Here's a post I wrote a while ago that clarifies some of the concepts around GraphQL: https://medium.com/apollo-stack/how-do-i-graphql-2fcabfc94a01

And here's a post that explains the interplay between GraphQL schemas and resolve functions: https://medium.com/apollo-stack/graphql-explained-5844742f195e

Solution 2:

Not sure if this is relevant to you because you want it to start with "jason" (ie would return "jason bourne" but not "bourne jason") but I recently came across a way to query GraphQL in a "%Like%" manner. For your use case it would look something like this:

export const allUsersQuery = `
  query allUsers($UserName: String!){
    allUsers(
      filter: {first_name_contains: $UserName}
    ) {
      id
      first_name
      ...INSERT_OTHER_FIELDS_HERE...
    }
  }
`;

FWIW: I did this using a GraphCool BAAS. I don't think you were using GraphCool because GraphCool doesn't allow "_" in variable names.

Hope this helps someone down the line :)