How to search string values in GraphQL

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)