UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Spring Boot】GraphQL Apollo Client でリクエスト時にヘッダーにAuth情報を含めたい

以前セットアップしたApollo Client でリクエスト時にヘッダーにAuth情報を含めたい

uga-box.hatenablog.com

設定方法は以下に書かれている

10. Authenticate your queries - Apollo GraphQL Docs

Kotlin用をJavaに読み替えて、以下のように書くけば良さそう

    OkHttpClient okHttp =
        new OkHttpClient.Builder()
            .addInterceptor(
                chain -> {
                  Request request =
                      chain
                          .request()
                          .newBuilder()
                          .method("POST", chain.request().body())
                          .addHeader("X-Api-Key", properties.getAuth().getKey())
                          .build();
                  return chain.proceed(request);
                })
            .build();

    ApolloClient client = ApolloClient.builder()
        .serverUrl("https://apollo-fullstack-tutorial.herokuapp.com/")
        .okHttpClient(okHttp)
        .build();

Spring boot 2.5系の場合エラーになる

上の実装をして実行したところ、以下のランタイムエラーが発生した

java.lang.NoSuchFieldError: Companion

これはcom.squareup.okhttp3:okhttp:4.xが期待される所でcom.squareup.okhttp3:okhttp:3.x が利用されたということで発生するエラー

下を見ると、確かにspring-bootのv2.5系のokhttpはokhttp3がv3系なので、これが原因だった

https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-dependencies/2.5.12/spring-boot-dependencies-2.5.12.pom

pomに直接okhttp3をv4系にあげてみるとエラーが発生しなくなった

動くようにはなったが、spring-bootが古いのはよくない状態なので、一旦はこれで様子を見てspring-bootのバージョンアップを検討する

参考

https://wrongwrong163377.hatenablog.com/entry/2022/01/19/192535