Skip to content

Instantly share code, notes, and snippets.

@ricardopsantos
Last active January 14, 2023 19:17
Show Gist options
  • Save ricardopsantos/bba542c9596ae8ed212dca3195b6fc14 to your computer and use it in GitHub Desktop.
Save ricardopsantos/bba542c9596ae8ed212dca3195b6fc14 to your computer and use it in GitHub Desktop.
Article_13_G8.swift
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