LocalData/Sources/LocalData/Models/AnyStorageKey.swift

31 lines
1.1 KiB
Swift

public struct AnyStorageKey: Sendable {
public internal(set) var descriptor: StorageKeyDescriptor
private let migrateAction: @Sendable (StorageRouter) async throws -> Void
public init<Key: StorageKey>(_ key: Key) {
self.descriptor = .from(key)
self.migrateAction = { router in
try await router.migrate(for: key)
}
}
private init(descriptor: StorageKeyDescriptor, migrateAction: @escaping @Sendable (StorageRouter) async throws -> Void) {
self.descriptor = descriptor
self.migrateAction = migrateAction
}
public static func key<Key: StorageKey>(_ key: Key) -> AnyStorageKey {
AnyStorageKey(key)
}
/// Internal use: Returns a copy of this key with the catalog name set.
internal func withCatalog(_ name: String) -> AnyStorageKey {
AnyStorageKey(descriptor: descriptor.withCatalog(name), migrateAction: migrateAction)
}
/// Internal use: Triggers the migration logic for this key.
internal func migrate(on router: StorageRouter) async throws {
try await migrateAction(router)
}
}