66// Copyright © 2015 PureSwift. All rights reserved.
77//
88
9+ import Predicate
10+
911/// CoreModel Store Protocol
1012public protocol ModelStorage : AnyObject {
1113
@@ -32,6 +34,8 @@ public extension ModelStorage {
3234 }
3335}
3436
37+ // MARK: - ModelData
38+
3539/// CoreModel Object Instance
3640public struct ModelData : Equatable , Hashable , Identifiable , Codable {
3741
@@ -55,3 +59,63 @@ public struct ModelData: Equatable, Hashable, Identifiable, Codable {
5559 self . relationships = relationships
5660 }
5761}
62+
63+ // MARK: - ModelStorage Codable Extensions
64+
65+ public extension ModelStorage {
66+
67+ /// Fetch managed object.
68+ func fetch< T> ( _ entity: T . Type , for id: ObjectID ) async throws -> T ? where T: Entity {
69+ guard let model = try await fetch ( T . entityName, for: id) else {
70+ return nil
71+ }
72+ return try T . init ( from: model)
73+ }
74+
75+ /// Fetch managed objects.
76+ func fetch< T> (
77+ _ entity: T . Type ,
78+ sortDescriptors: [ FetchRequest . SortDescriptor ] = [ ] ,
79+ predicate: Predicate ? = nil ,
80+ fetchLimit: Int = 0 ,
81+ fetchOffset: Int = 0
82+ ) async throws -> [ ModelData ] where T: Entity {
83+ let fetchRequest = FetchRequest (
84+ entity: T . entityName,
85+ sortDescriptors: sortDescriptors,
86+ predicate: predicate,
87+ fetchLimit: fetchLimit,
88+ fetchOffset: fetchOffset
89+ )
90+ return try await fetch ( fetchRequest)
91+ }
92+
93+ /// Fetch and return result count.
94+ func count< T> (
95+ _ entity: T . Type ,
96+ sortDescriptors: [ FetchRequest . SortDescriptor ] = [ ] ,
97+ predicate: Predicate ? = nil ,
98+ fetchLimit: Int = 0 ,
99+ fetchOffset: Int = 0
100+ ) async throws -> UInt where T: Entity {
101+ let fetchRequest = FetchRequest (
102+ entity: T . entityName,
103+ sortDescriptors: sortDescriptors,
104+ predicate: predicate,
105+ fetchLimit: fetchLimit,
106+ fetchOffset: fetchOffset
107+ )
108+ return try await count ( fetchRequest)
109+ }
110+
111+ /// Create or edit a managed object.
112+ func insert< T> ( _ value: T ) async throws where T: Entity , T: Encodable {
113+ let model = value. encode ( )
114+ try await insert ( model)
115+ }
116+
117+ /// Delete the specified managed object.
118+ func delete< T> ( _ entity: T . Type , for id: ObjectID ) async throws where T: Entity {
119+ try await delete ( T . entityName, for: id)
120+ }
121+ }
0 commit comments