GraphQL SPQR fetches all fields on the server side

618 views Asked by At

I'm new to Spring Boot and I just started using graphql-spqr for Spring Boot since it allows for easy bootstrapping of Java projects.

However, as per my understanding, GraphQL basically allows the fetching of selected fields from the database. As per the examples, I've seen, this type of selection in the graphql-spqr library happens on the client side. Is there a way to do selection both client-side and server-side so as to speed up the queries?

I've looked into EntityGraph examples for GraphQL but they are mostly implemented for complex queries that involve JOINs. However, nothing exists for simple queries like findAll(), findById() etc.

I would like to use findAll() with the server fetching only the fields as requested by the client. How can I do that?

1

There are 1 answers

0
kaqqao On BEST ANSWER

What was said in the comments is correct: GraphQL (and hence SPQR, as it's merely a tool to hook the schema up) does not know anything about SQL, databases, JOINs or anything else. It's a communication protocol, the rest is up to you. As for your situation, you'd have to inject the subselection into the resolver and pass it down to SQL. In the simplest case, it can look like this (in pseudo code):

public List<Book> books(@GraphQLEnvironment Set<String> fields) {
    //pass the requested field names further
    return database.query("SELECT " + fields + " FROM book");
}

You can inject ResolutionEnvironment using the same annotation, in case you need the full context.