Skip to content

Instantly share code, notes, and snippets.

@mironal
Created February 15, 2023 00:46
Show Gist options
  • Save mironal/b74c2b8548a246eaa55ffe1001608432 to your computer and use it in GitHub Desktop.
Save mironal/b74c2b8548a246eaa55ffe1001608432 to your computer and use it in GitHub Desktop.
KeychainStorageEngine.swift implementation for Bodega with KeychainAccess
import Bodega // https://github.com/mergesort/Bodega
import Foundation
import KeychainAccess // https://github.com/kishikawakatsumi/KeychainAccess
public actor KeychainStorageEngine: StorageEngine {
private let keychain: Keychain
init(keychain: Keychain) {
self.keychain = keychain
}
public func write(_ data: Data, key: Bodega.CacheKey) throws {
try keychain.set(data, key: key.value)
}
public func write(_ dataAndKeys: [(key: Bodega.CacheKey, data: Data)]) throws {
for dataAndKey in dataAndKeys {
try write(dataAndKey.data, key: dataAndKey.key)
}
}
public func read(key: Bodega.CacheKey) async -> Data? {
keychain[data: key.value]
}
public func readDataAndKeys(keys: [Bodega.CacheKey]) async -> [(key: Bodega.CacheKey, data: Data)] {
keys.compactMap {
guard let data = keychain[data: $0.value] else { return nil }
return (key: $0, data: data)
}
}
public func remove(key: Bodega.CacheKey) async throws {
try keychain.remove(key.value)
}
public func removeAllData() throws {
try keychain.removeAll()
}
public func keyExists(_ key: Bodega.CacheKey) async -> Bool {
keychain.allKeys().contains(key.value)
}
public func keyCount() async -> Int {
keychain.allKeys().count
}
public func allKeys() async -> [Bodega.CacheKey] {
keychain.allKeys().map { .init($0) }
}
public func createdAt(key: Bodega.CacheKey) async -> Date? {
keychain[attributes: key.value]?.creationDate
}
public func updatedAt(key: Bodega.CacheKey) async -> Date? {
keychain[attributes: key.value]?.modificationDate
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment