Last active
July 22, 2024 12:57
-
-
Save leogdion/aa10a26127c11123f84f8fb3a6462be8 to your computer and use it in GitHub Desktop.
Sample Code for ModelActor
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 protocol Database: Sendable { | |
func delete<T: PersistentModel>( | |
where predicate: Predicate<T>? | |
) async throws | |
func insert(_ closuer: @Sendable @escaping () -> some PersistentModel) async | |
func fetch<T, U : Sendable>( | |
_ selectDescriptor: @escaping @Sendable () -> FetchDescriptor<T>, | |
with closure: @escaping @Sendable ([T]) throws -> U | |
) async throws -> U | |
func fetch<T, U : Sendable>( | |
for objectID: PersistentIdentifier, | |
with closure: @escaping @Sendable (T?) throws -> U | |
) async throws -> U? where T: PersistentModel | |
func transaction(_ block: @Sendable @escaping (ModelContext) throws -> Void) async throws | |
} | |
extension Database { | |
public static var loggingCategory: BushelLogging.Category { | |
.data | |
} | |
public func deleteAll(of types: [any PersistentModel.Type]) async throws { | |
try await self.transaction { context in | |
try types.forEach { | |
try context.delete(model: $0) | |
} | |
} | |
} | |
public func delete<T: PersistentModel>( | |
model _: T.Type, | |
where predicate: Predicate<T>? = nil | |
) async throws { | |
try await self.delete(where: predicate) | |
} | |
func fetch<T, U : Sendable>( | |
_ modelID: ModelID<T>, | |
with closure: @escaping @Sendable (T?) throws -> U | |
) async throws -> U? where T: PersistentModel { | |
try await self.fetch(for: modelID.persistentIdentifier, with: closure) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment