Last active
January 14, 2023 19:17
-
-
Save ricardopsantos/bba542c9596ae8ed212dca3195b6fc14 to your computer and use it in GitHub Desktop.
Article_13_G8.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public func syncRetrieve<T: Codable>(_ some: T.Type, key: String, params: [String]) -> (model: T, recordDate: Date)? { | |
var cachedRecords: [ExpiringCodableObjectWithKey] { | |
let records: [CDataExpiringKeyValueEntety] = Self.nonSecureInstanceSync.fetch() | |
return records .compactMap { record in | |
let encoding = ExpiringCodableObjectWithKey.ValueEncoding(rawValue: Int(record.encoding)) ?? .dataPlain | |
let model = ExpiringCodableObjectWithKey(key: record.key!, | |
expireDate: record.expireDate!, | |
object: record.object!, | |
objectType: record.objectType!, | |
encoding: encoding) | |
return model | |
} | |
} | |
let composedKey = ExpiringCodableObjectWithKey.composedKey(key, params) | |
if let record = cachedRecords | |
.filter({ $0.key == composedKey && !$0.isExpired }) | |
.sorted(by: { a, b in | |
a.recordDate > b.recordDate | |
}) | |
.first { | |
if let extracted = record.extract(T.self) { | |
return (extracted, record.recordDate) | |
} | |
} | |
return nil | |
} | |
func syncStore<T: Codable>(_ codable: T, key: String, params: [String], timeToLiveMinutes: Int?) { | |
let toStore = ExpiringCodableObjectWithKey(codable, | |
key: key, | |
params: params, | |
timeToLiveMinutes: timeToLiveMinutes) | |
let newInstance: CDataExpiringKeyValueEntety = Self.nonSecureInstanceSync.createEntity() | |
newInstance.key = toStore.key | |
newInstance.recordDate = toStore.recordDate | |
newInstance.expireDate = toStore.expireDate | |
newInstance.encoding = Int16(toStore.encoding) | |
newInstance.object = toStore.object | |
newInstance.objectType = toStore.objectType | |
Self.nonSecureInstanceSync.saveContext() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment