캐시 정책
아폴로에서 캐시 사용에 대한 정책으로 캐시 동작 방식이 바뀐다.
공식 문서에 나와있는 내용인데, 세 개의 핵심적인 내용은 다음과 같다.
- A read function that specifies what happens when the field's cached value is read
- 캐시 데이터를 정제해주는 방식을 지정할 수 있다.
- A merge function that specifies what happens when field's cached value is written
- 캐시 데이터가 업데이트 될 때, 업데이트 될 데이터를 정제해주는 방식를 지정할 수 있다.
- 서버에서 받은 데이터를 캐시에 업데이트 할 때나 writeQuery 를 사용하여 프론트에서 캐시를 업데이트 할 때 등 캐시를 업데이트할 때 동작한다.
- An array of key arguments that help the cache avoid storing unnecessary duplicate data.
- 쿼리를 날릴 때 캐시 정책을 지정할 수 있다. 해당 내용은 아래에 구체적인 예시를 통해 설명한다.
keyArgs에 따라 캐시 플랜이 바뀐다.
keyArgs는 데이터가 argument 중 어떤 필드 기준으로 캐싱될지를 정해주는 옵션이다. false로 지정하면 모든 argument를 고려해서 캐싱한다. 아래 예시를 보자.
// query 1
variables: {
model: 'customer',
type: 'A',
start: 0,
}
// query 2
variables: {
model: 'customer',
type: 'A',
start: 10,
}
// query 3
variables: {
model: 'bank',
type: 'B',
start: 0,
}
위와 같은 요청을 날린다고 했을 때, keyArgs: ["type"]로 두면 query1 이후 query2 요청을 날렸을 때는 hit된다. query3은 type이 다르므로 hit되지 않고 새로 불러오게 된다.
keyArgs: false로 두면 model, type, start가 전부 같은 경우에만 hit된다. query1을 날리고 query1을 다시 날리는 경우가 이에 해당한다.
더 구체적인 방식으로 캐시 정책을 지정하려면 함수를 지정할 수도 있다.
참고한 자료
https://www.apollographql.com/docs/react/caching/cache-field-behavior/
https://harimkim.netlify.app/2021-04-til-apollo-client-v2-to-v3-next-js-link/