[swift] 스위프트 아폴로를 사용한 캐시 유효성 검사 방법

이번 포스트에서는 Swift 언어에서 아폴로(Apollo)를 사용하여 캐시의 유효성을 검사하는 방법에 대해 알아보겠습니다.

아폴로는 GraphQL을 위한 클라이언트 라이브러리로, 데이터를 캐시하고 관리하는 기능을 제공합니다. 캐시는 네트워크 요청을 줄여주고, 앱의 성능을 향상시킬 수 있습니다. 하지만 때로는 캐시의 내용이 유효하지 않아 업데이트되어야 하는 상황이 발생합니다. 이때 캐시의 유효성을 검사하는 것이 중요합니다.

1. 유형별로 캐시 검사하기

캐시의 유효성을 검사하는 가장 일반적인 방법은 각 유형별로 검사하는 것입니다. 유형은 쿼리(Query), 뮤테이션(Mutation), 구독(Subscription) 등의 동작에 따라 달라질 수 있습니다.

1.1. 쿼리 검사

쿼리의 경우, 서버로부터 받아온 데이터와 캐시된 데이터를 비교하여 유효성을 검사할 수 있습니다. 예를 들어, 쿼리 요청 시 서버의 응답에 포함된 updatedAt 필드와 캐시의 해당 필드를 비교하여 캐시를 업데이트할지 여부를 결정할 수 있습니다.

import Apollo

func fetchPosts() {
    Apollo.shared.fetch(query: GetPostsQuery()) { result in
        switch result {
        case .success(let result):
            if let serverUpdatedAt = result.data?.posts.updatedAt,
               let cachedUpdatedAt = Apollo.shared.cache["GetPostsQuery"]?.data?.posts.updatedAt,
               serverUpdatedAt > cachedUpdatedAt {
                // 캐시 업데이트 로직 수행
            }
        case .failure(let error):
            // 에러 처리
        }
    }
}

1.2 뮤테이션 검사

뮤테이션의 경우, 쿼리와 동일하게 서버의 응답과 캐시를 비교하여 유효성을 검사할 수 있습니다. 예를 들어, 새로운 포스트를 작성하는 뮤테이션을 수행한 후, 캐시된 포스트 목록의 count를 업데이트하고자 할 때 아래와 같이 검사할 수 있습니다.

import Apollo

func createPost() {
    Apollo.shared.perform(mutation: CreatePostMutation()) { result in
        switch result {
        case .success(let result):
            if let serverCount = result.data?.createPost.count,
               let cachedCount = Apollo.shared.cache["GetPostsQuery"]?.data?.posts.count,
               serverCount != cachedCount {
                // 캐시 업데이트 로직 수행
            }
        case .failure(let error):
            // 에러 처리
        }
    }
}

2. 지연 유효성 검사하기

지연 유효성 검사 방법은 캐시 업데이트를 미루는 방법입니다. 데이터를 가져오는 시점에 캐시의 유효성을 검사하지 않고, 필요할 때 검사하여 캐시 업데이트를 수행합니다.

2.1. 동기식 지연

동기식 지연 유효성 검사는 데이터를 요청하고 받은 후에 캐시의 유효성을 검사 및 업데이트하는 방식입니다. 예를 들어, 포스트 상세 페이지를 표시하기 전에 최신 데이터인지 확인하고 업데이트할 수 있습니다.

import Apollo

func fetchPostDetail(postId: String) {
    Apollo.shared.fetch(query: GetPostDetailQuery(postId: postId)) { result in
        switch result {
        case .success(let result):
            if let serverUpdatedAt = result.data?.postDetail.updatedAt,
               let cachedUpdatedAt = Apollo.shared.cache["GetPostDetailQuery"]?.data?.postDetail.updatedAt,
               serverUpdatedAt > cachedUpdatedAt {
                // 캐시 업데이트 로직 수행
            } else {
                // 캐시 사용 로직 수행
            }
        case .failure(let error):
            // 에러 처리
        }
    }
}

2.2. 비동기식 지연

비동기식 지연 유효성 검사는 데이터를 요청한 후, 캐시의 유효성을 검사하는 동안 로딩 상태를 표시하거나 기타 작업을 수행할 수 있는 방식입니다. 예를 들어, 포스트 목록을 로딩하는 동안 유효성을 검사하여 업데이트할 수 있습니다.

import Apollo

func fetchPosts() {
    Apollo.shared.fetch(query: GetPostsQuery()) { result in
        switch result {
        case .success(let result):
            if let serverUpdatedAt = result.data?.posts.updatedAt,
               let cachedUpdatedAt = Apollo.shared.cache["GetPostsQuery"]?.data?.posts.updatedAt,
               serverUpdatedAt > cachedUpdatedAt {
                // 캐시 업데이트 로직 수행
            } else {
                // 캐시 사용 로직 수행
            }
        case .failure(let error):
            // 에러 처리
        }
    }
}

결론

이렇게 쿼리와 뮤테이션을 통해 아폴로의 캐시의 유효성을 검사하는 방법에 대해 알아보았습니다. 이를 통해 앱의 성능을 향상시키고, 항상 최신 데이터를 유지할 수 있습니다. 자세한 내용은 아폴로 공식 문서를 참고하시기 바랍니다.