Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
52 views
in Technique[技术] by (71.8m points)

How to search string values in GraphQL

How do you query using GraphQL in a manor similar to SQL's like operator?

Example: What users have a first name starting with jason?

select * from users where first_name like "jason%"

question from:https://stackoverflow.com/questions/37981269/how-to-search-string-values-in-graphql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...