summaryrefslogtreecommitdiff
path: root/Hutch/Networking/SystemStatusCacheStore.swift
blob: 63c64b967a00285a9f37549766df9f518d865f9d (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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import Foundation

actor SystemStatusCacheStore {
    private let snapshotCacheKey = "systemStatusSnapshotCache"
    private let incidentCacheKey = "systemStatusIncidentCache"
    private let defaults: UserDefaults

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
    }

    func loadSnapshotHTML() -> (html: String, timestamp: Date)? {
        guard let html = defaults.string(forKey: snapshotCacheKey) else {
            return nil
        }

        let timestampValue = defaults.double(forKey: snapshotTimestampKey)
        guard timestampValue > 0 else {
            defaults.removeObject(forKey: snapshotCacheKey)
            defaults.removeObject(forKey: snapshotTimestampKey)
            return nil
        }

        return (html, Date(timeIntervalSince1970: timestampValue))
    }

    func saveSnapshotHTML(_ html: String, timestamp: Date) {
        defaults.set(html, forKey: snapshotCacheKey)
        defaults.set(timestamp.timeIntervalSince1970, forKey: snapshotTimestampKey)
    }

    func loadIncidentFeedData() -> (data: Data, timestamp: Date)? {
        guard let data = defaults.data(forKey: incidentCacheKey) else {
            return nil
        }

        let timestampValue = defaults.double(forKey: incidentTimestampKey)
        guard timestampValue > 0 else {
            defaults.removeObject(forKey: incidentCacheKey)
            defaults.removeObject(forKey: incidentTimestampKey)
            return nil
        }

        return (data, Date(timeIntervalSince1970: timestampValue))
    }

    func saveIncidentFeedData(_ data: Data, timestamp: Date) {
        defaults.set(data, forKey: incidentCacheKey)
        defaults.set(timestamp.timeIntervalSince1970, forKey: incidentTimestampKey)
    }

    private var snapshotTimestampKey: String {
        "\(snapshotCacheKey).timestamp"
    }

    private var incidentTimestampKey: String {
        "\(incidentCacheKey).timestamp"
    }
}