typePolicies (apollo)
InMemoryCache (apollo)のoptionの1つ
各 __typename に対して、キャッシュの扱い方を定義する
docs
型
code:ts
typePolicies?: Record<string, TypePolicy>;
例:ページネーションの制御も可能
code:ts
typePolicies: {
Query: {
fields: {
allProducts: {
keyArgs: false, // 全てのクエリ結果を1つにマージ
merge(existing = [], incoming) {
return ...existing, ...incoming;
},
},
},
},
}
gpt-5.icon
GraphQL の「型(Type)」単位で、
どのフィールドを ID として扱うか
keyFields (apollo)
同じオブジェクトが重複してきたときどうマージするか(merge)
キャッシュから読み出す時にどう振る舞うか(read)
Query 型のフィールドごとのキャッシュ戦略(keyArgs, merge)
などを細かく制御できます。
以下、実務でよく使うパターン順に整理して解説します。
1. 全体像:InMemoryCache の typePolicies
だいたいこんな形で定義します:
code:ts
import { InMemoryCache } from "@apollo/client";
const cache = new InMemoryCache({
typePolicies: {
User: { // GraphQLの type User に対するポリシー
keyFields: "id",
fields: {
fullName: {
read(existing, { readField }) {
const firstName = readField<string>("firstName");
const lastName = readField<string>("lastName");
return ${firstName} ${lastName};
},
},
},
},
Query: {
fields: {
users: {
keyArgs: false,
merge(existing = [], incoming: any[]) {
return ...existing, ...incoming;
},
},
},
},
},
});
typePolicies のキーは GraphQL スキーマの type 名(User, Query, Job, etc.)
その中で
keyFields … その型の「主キー」を指定
fields … その型の各フィールド単位で read/merge などを設定
keyFields (apollo)
keyArgs (apollo)
4. fields / read / merge: 型のフィールドごとのカスタマイズ
typePolicies の中の fields は、
オブジェクト型のフィールド
Query / Mutation のフィールド
の両方に対して設定できます。
code:ts
typePolicies: {
User: {
fields: {
fullName: {
read(existing, { readField }) {
const first = readField<string>("firstName");
const last = readField<string>("lastName");
return ${first} ${last};
},
},
},
},
}
read (apollo)
merge (apollo)