Skip to content

Instantly share code, notes, and snippets.

@leogdion
Last active July 22, 2024 12:57
Show Gist options
  • Save leogdion/aa10a26127c11123f84f8fb3a6462be8 to your computer and use it in GitHub Desktop.
Save leogdion/aa10a26127c11123f84f8fb3a6462be8 to your computer and use it in GitHub Desktop.
Sample Code for ModelActor
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