ApolloClient におけるFragment Matcher
Motivation
以下のようなエラーが吐かれたので調べる。
code:shell
You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types. Apollo Client will not be able to accurately map fragments. To make this error go away, use the IntrospectionFragmentMatcher as described in the docs: https://www.apollographql.com/docs/react/recipes/fragment-matching.html
WARNING: heuristic fragment matching going on!
なにをしたか?
言われているのは、つまりこういうことだと思う。
code:graphql
interface Hoge { ... }
fuga {
... on Hoge {
...
}
}
GraphQL には Fragment というものがあり、型がマッチングした場合にのみその値を取り出すことができる。ただ、ApolloClient では Interface や Union 型に対して Fragment を利用する場合には IntrospectionFragmentMatcher という matcher を特別に指定する必要があるらしい。
どう設定するか?
FragmentMatcher はキャッシュの設定に追加すれば良いようだ。
https://www.apollographql.com/docs/react/advanced/caching.html
詳しい話は以下にある。
https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher
ここに示されている例だと、all_people は全てのキャラクター Character[] を取得する queryで、Jedi, Droid は Character の具象型。しかし、クライアントサイドではこの「具象型である」という情報はスキーマに関する情報なしでは (= サーバからのレスポンスだけでは) わからない。
code:graphql
query {
all_people {
... on Character {
name
}
... on Jedi {
side
}
... on Droid {
model
}
}
}
ApolloClient のキャッシュ機構がデフォルトで利用する heuristic fragment macher では、「フラグメントで指定した型のフィールドが全て含まれていれば、該当のフラグメントにマッチさせる」という手法をとる。
しかし、たぶんこの方法の場合、interface, union のスキーマ情報がわからないといけない。そのため、キャッシュ機構にスキーマ情報を渡してやる必要がある、ということか?