aboutsummaryrefslogtreecommitdiff
path: root/Hutch/Networking/ResponseCache.swift
blob: a6cc26917a3e4bb37154517897d3dc7b5213ab81 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import Foundation
import os

/// Thread-safe in-memory cache for raw GraphQL response data.
/// Keyed by a caller-provided string (typically service name + query hash).
final class ResponseCache: Sendable {

    private let storage: OSAllocatedUnfairLock<[String: Data]>

    init() {
        self.storage = OSAllocatedUnfairLock(initialState: [:])
    }

    /// Store raw response data under a cache key.
    func set(_ data: Data, forKey key: String) {
        storage.withLock { $0[key] = data }
    }

    /// Retrieve cached response data. Returns nil on cache miss.
    func get(forKey key: String) -> Data? {
        storage.withLock { $0[key] }
    }

    /// Remove a specific entry.
    func remove(forKey key: String) {
        storage.withLock { _ = $0.removeValue(forKey: key) }
    }

    /// Clear all cached data (e.g. on sign-out).
    func clear() {
        storage.withLock { $0.removeAll() }
    }
}