Reputation: 190
So the thing i try to do is, retrieve filtered data from the Database (MongoDB in my situation) using GraphQL.
Speaking in "MySQL language" how to implement the where
clause in GraphQL?
I followed this tutorial : https://learngraphql.com/basics/using-a-real-data-source/5
Query with filter was defined like this :
const Query = new GraphQLObjectType({
name: "Queries",
fields: {
authors: {
type: new GraphQLList(Author),
resolve: function(rootValue, args, info) {
let fields = {};
let fieldASTs = info.fieldASTs;
fieldASTs[0].selectionSet.selections.map(function(selection) {
fields[selection.name.value] = 1;
});
return db.authors.find({}, fields).toArray();
}
}
}
});
The tricky part here is the info
parameter in the resolve
function. Some explanations i've found here : http://pcarion.com/2015/09/26/graphql-resolve/
So it is AST (Abstract Syntax Tree)
Can anyone please provide some basic real-life example code that would show how to define and execute the following query : Get all authors where name == John
Thank you!
Upvotes: 1
Views: 3859
Reputation: 3909
There is no need to examine the AST. That would be awfully laborious.
All you need to do is define an argument on the author
field. This is the second paramenter of the resolver, so you can check for that arguement and include it in the Mongo query.
const Query = new GraphQLObjectType({
name: "Queries",
fields: {
authors: {
type: new GraphQLList(Author),
// define the arguments and their types here
args: {
name: { type: GraphQLString }
},
resolve: function(rootValue, args, info) {
let fields = {};
// and now you can check what the arguments' values are
if (args.name) {
fields.name = args.name
}
// and use it when constructing the query
return db.authors.find(fields, fields).toArray();
}
}
}
});
Upvotes: 2