0

Is it possible to not have to wait for the parent @GraphQLContext resolver to fully resolve before executing the child-resolvers?

By looking at the source code I figured this might be possible by leveraging futures, something like so:

@GraphQLQuery
public Future<User> user() {
    return CompletableFuture.supplyAsync(...);
}

@GraphQLQuery
public TwitterProfile twitterProfile(@GraphQLContext Future<User> user) {
    ...
}

Any ideas?

kaqqao
  • 12,984
  • 10
  • 64
  • 118
William Boman
  • 2,079
  • 5
  • 26
  • 39

1 Answers1

2

You can compose an async chain using CompletionStage (of which a CompletableFuture is a subtype). Simple Future isn't enough as it doesn't allow composition. This is a feature of graphql-java itself, not SPQR specifically.

@GraphQLQuery
public CompletableFuture<User> user() {
    return CompletableFuture.supplyAsync(...);
}

@GraphQLQuery
public TwitterProfile twitterProfile(@GraphQLContext User user) {
    ...
}

Note that the threading and concurrency is still fully under your control. This just lets you compose async resolvers as appropriate, but you need to actually start a thread that will complete the promise yourself (e.g. via supplyAsync). This also means fields on the same level can be resolved concurrently.

That said, the GraphQL spec mandates the parent field is resolved before the children:

the object value being evaluated and the object type need to be known

(emphasis mine). This is mostly because the result of the parent query is needed for the children to resolve, not some special constraint. If you have a field that is truly independent of its parent, I'd go as far as to argue it should not have a parent in the first place.

kaqqao
  • 12,984
  • 10
  • 64
  • 118