0
votes

We are planning to use graphql for orchestrations (For e.g. UI client invokes graphql service which goes to multiple rest endpoint and return the result). Problem here is from one rest endpoint we have to pass different types of query parameters based on the field requested by our client.

We use spring-boot-graphql and graphql-java-tools libraries to initialize graphql

type Query{
  user(id: ID): User
}

type User{
 phone: [Phone]
 address: [Address]
}

type Phone{...}
type Address{...}

My code resolves user field and invoke rest endpoint to fetch phone and address information in a single call like https:restservice.com\v1\user\123?fields=phone,address

How to resolve two fields expecting data from same rest service. I want something like when client request for phone then i needs to send fields in request parameters as phone alone without address. Can we do that? or is there any other way to define schema to solves this problem?

1

1 Answers

0
votes
query {
    user(userId : "xyz")  {
        name
        age
        weight
        friends {
            name
        }
    }
}

Knowing the field selection set can help make DataFetchers more efficient. For example in the above query imagine that the user field is backed by an SQL database system. The data fetcher could look ahead into the field selection set and use different queries because it knows the caller wants friend information as well as user information.

    DataFetcher smartUserDF = new DataFetcher() {
        @Override
        public Object get(DataFetchingEnvironment env) {
            String userId = env.getArgument("userId");

            DataFetchingFieldSelectionSet selectionSet = env.getSelectionSet();
            if (selectionSet.contains("user/*")) {
                return getUserAndTheirFriends(userId);
            } else {
                return getUser(userId);
            }
        }
    };

https://www.graphql-java.com/documentation/v12/fieldselection/