Adding request header to a graphql request using HttpGraphQlClient client

1.7k Views Asked by At

Is there any way to attach a header at the request level to HttpGraphQlClient without client regeneration. I want to attach individual session id of the user to the graphql request.

2

There are 2 best solutions below

0
On

Without knowing more about how you're getting this session id, I think you can use an ExchangeFilterFunction for that:

ClientSessionFilterFunction sessionFilter = new ClientSessionFilterFunction();
WebClient.Builder builder = WebClient.builder().filter(sessionFilter);



public class ClientSessionFilterFunction implements ExchangeFilterFunction {

    @Override
    public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
        Mono<String> sessionId = //...
        return sessionId.flatMap(id -> {
            request.headers().add("Session-Id", id);
            return next.exchange(request);
        });
    }
}

0
On

The solution I found in the official documentation is this:

Once HttpGraphQlClient is created, you can begin to execute requests using the same API, independent of the underlying transport. If you need to change any transport specific details, use mutate() on an existing HttpGraphQlClient to create a new instance with customized settings.

So my class looks like this:

@Component
public class MyGraphqlClient {
    @Autowired
    private HttpGraphQlClient graphQlClient; // a preconfigured bean, used as a prototype

    public Mono<MyResponse> getCompany(String input) {
        return graphQlClient.mutate()
                .header("x-my-header", "MY_VALUE") // Here I set my request-specific header
                .build()

                .documentName("NAME OF THE RESOURCE in resources/graphql-documents")
                .variable("input", input)
                .retrieve("QUERY_NAME")
                .toEntity(MyResponse.class)
                ;
    }
}

It is not completely "without client regeneration" as you requested, but at least the pre-generated client is re-used as a prototype, and I don't have to set up all its parameters again. And it's in accordance with the official documentation. I would like a better solution, too :)