Skip to content

Commit

Permalink
Refactor StatProvider to improve data fetching logic and enhance docu…
Browse files Browse the repository at this point in the history
…mentation
  • Loading branch information
kasianov-mikhail committed Dec 6, 2024
1 parent 5666688 commit 3c10495
Showing 1 changed file with 37 additions and 20 deletions.
57 changes: 37 additions & 20 deletions Sources/Scout/UI/StatProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,58 +21,75 @@ import CloudKit
self.eventName = eventName
}

/// Fetches the statistical data if it has not been fetched yet.
/// - Parameter container: The CloudKit container from which to fetch the data.
/// Fetches data if needed from the provided database.
///
/// This asynchronous function checks if the data needs to be fetched and performs the fetch operation
/// using the given `DatabaseController` instance.
///
/// - Parameter database: The `DatabaseController` instance used to fetch the data.
/// - Returns: An asynchronous operation that fetches the data if needed.
///
func fetchIfNeeded(in database: DatabaseController) async {
if data == nil {
await fetch(in: database)
}
}
}

// MARK: - Fetching Data

/// Fetches the statistical data from the CloudKit container.
/// - Parameter container: The CloudKit container from which to fetch the data.
extension StatProvider {

/// Fetches data from the specified database asynchronously.
///
/// - Parameter database: The `DatabaseController` instance from which to fetch data.
///
private func fetch(in database: DatabaseController) async {
let today = Calendar(identifier: .iso8601).startOfDay(for: Date())
let yearAgo = today.addingYear(-1).addingWeek(-1)

let predicate = NSPredicate(
format: "date >= %@ AND name == %@",
yearAgo as NSDate,
eventName
)

let query = CKQuery(
recordType: "DateIntMatrix",
predicate: predicate
)

do {
let records = try await database.allRecords(
matching: query,
matching: query(from: yearAgo),
desiredKeys: nil
)

let points = try records.map(Matrix.init)
let rawPoints = try records.map(Matrix.init)
.mergeDuplicates()
.flatMap(ChartPoint.fromIntMatrix)

let series = RawPointData(
let rawData = RawPointData(
from: yearAgo,
to: today.addingDay(),
points: points
points: rawPoints
)

data = series.chartData(for: StatPeriod.components)
data = rawData.chartData(for: StatPeriod.components)

} catch {
print(error.localizedDescription)
data = nil
}
}

private func query(from date: Date) async throws -> CKQuery {
let predicate = NSPredicate(
format: "date >= %@ AND name == %@",
date as NSDate,
eventName
)

let query = CKQuery(
recordType: "DateIntMatrix",
predicate: predicate
)

return query
}
}

// MARK: - Calendar Components

extension StatPeriod {

/// A set of calendar components used for date calculations.
Expand Down

0 comments on commit 3c10495

Please sign in to comment.