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 Answers
The solution I found in the official documentation is this:
Once
HttpGraphQlClientis 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, usemutate()on an existingHttpGraphQlClientto 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.
Nevertheless, I would like to have a better solution :) It still creates a new client, but at least "not as much" as creating it from scratch.
Comments
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);
});
}
}