From d7edbee9976e47e47e70db10dae8b5e5a44c6a9f Mon Sep 17 00:00:00 2001 From: Shial Date: Wed, 11 Jul 2018 23:29:52 +1000 Subject: [PATCH] [0.2.0] Move coredata serializer as an extension to LazeKit --- README.md | 9 +- SLazeKit.podspec | 3 +- SLazeKit.xcodeproj/project.pbxproj | 28 --- .../SLazeKit/Extensions/NSManagedObject.swift | 38 ---- .../Extensions/NSManagedObjectContext.swift | 23 --- .../SLazeKit/Protocols/EntityMapping.swift | 61 ------- .../Protocols/LazeConfiguration.swift | 11 +- Sources/SLazeKit/SLazeKit.swift | 19 +- Tests/SLazeKitTests/Models/Model.swift | 170 ------------------ Tests/SLazeKitTests/Models/Object.swift | 55 ------ 10 files changed, 14 insertions(+), 403 deletions(-) delete mode 100644 Sources/SLazeKit/Extensions/NSManagedObject.swift delete mode 100644 Sources/SLazeKit/Extensions/NSManagedObjectContext.swift delete mode 100644 Sources/SLazeKit/Protocols/EntityMapping.swift delete mode 100644 Tests/SLazeKitTests/Models/Model.swift delete mode 100644 Tests/SLazeKitTests/Models/Object.swift diff --git a/README.md b/README.md index 1839efa..143309a 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ SLazeKit is an easy to use Swift restful collection of extensions and classes. D **SLazeKit allows you:** - map your models by `Codable` protocol -- serialize `CoreData` models from API response +- serialize `CoreData` models from API response with [SLazeCoreData](https://github.com/shial4/SLazeCoreData.git) extension - fast and simple extend your models with `API` & `CoreData`

@@ -124,10 +124,11 @@ extension Default { } } - /// Required override of this method which will provide Context for bacground execution. + /// Method dedicated to be use for synchronize object into persisten store /// - /// - Returns: NSManagedObjectContext - open class func newBackgroundContext() -> NSManagedObjectContext? { return nil } + /// - Parameter obj: encoded object + /// - Throws: error occured during the process + open static func synchronize(_ obj: Any) {} } ``` diff --git a/SLazeKit.podspec b/SLazeKit.podspec index 44eeb55..db4fb23 100644 --- a/SLazeKit.podspec +++ b/SLazeKit.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'SLazeKit' - s.version = '0.1.9' + s.version = '0.2.0' s.summary = 'Swift restful manager.' s.description = <<-DESC SLazeKit is an easy to use Swift restful collection of extensions and classes. Don't spend hours writing your code to map your rest api request into models and serialization. stop wasting your time! @@ -14,6 +14,5 @@ Pod::Spec.new do |s| s.source = { :git => 'https://github.com/shial4/SLazeKit.git', :tag => s.version.to_s } s.source_files = 'Sources/**/*.swift' - s.frameworks = 'CoreData' end \ No newline at end of file diff --git a/SLazeKit.xcodeproj/project.pbxproj b/SLazeKit.xcodeproj/project.pbxproj index 3053c23..f9e174f 100644 --- a/SLazeKit.xcodeproj/project.pbxproj +++ b/SLazeKit.xcodeproj/project.pbxproj @@ -23,18 +23,13 @@ /* Begin PBXBuildFile section */ 623922782002D8C30018982A /* LazeConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 623922762002D8C30018982A /* LazeConfiguration.swift */; }; 6239227E2002DF1A0018982A /* Laze.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6239227D2002DF1A0018982A /* Laze.swift */; }; - 625B23AD1FF3462B001976C3 /* Object.swift in Sources */ = {isa = PBXBuildFile; fileRef = 625B23AB1FF34625001976C3 /* Object.swift */; }; 625B5F8F202288E700E72BCF /* StringPathTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 625B5F8E202288E700E72BCF /* StringPathTests.swift */; }; OBJ_32 /* Package.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_6 /* Package.swift */; }; - OBJ_38 /* Model.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_21 /* Model.swift */; }; OBJ_39 /* SLazeKitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_22 /* SLazeKitTests.swift */; }; OBJ_40 /* StringInitializableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_23 /* StringInitializableTests.swift */; }; OBJ_42 /* SLazeKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = "SLazeKit::SLazeKit::Product" /* SLazeKit.framework */; }; OBJ_49 /* Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_10 /* Decodable.swift */; }; - OBJ_50 /* NSManagedObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_11 /* NSManagedObject.swift */; }; - OBJ_51 /* NSManagedObjectContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_12 /* NSManagedObjectContext.swift */; }; OBJ_52 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_13 /* String.swift */; }; - OBJ_53 /* EntityMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_15 /* EntityMapping.swift */; }; OBJ_54 /* StringInitializable.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_16 /* StringInitializable.swift */; }; OBJ_55 /* SLazeKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_17 /* SLazeKit.swift */; }; /* End PBXBuildFile section */ @@ -59,16 +54,11 @@ /* Begin PBXFileReference section */ 623922762002D8C30018982A /* LazeConfiguration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LazeConfiguration.swift; sourceTree = ""; }; 6239227D2002DF1A0018982A /* Laze.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Laze.swift; sourceTree = ""; }; - 625B23AB1FF34625001976C3 /* Object.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Object.swift; sourceTree = ""; }; 625B5F8E202288E700E72BCF /* StringPathTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringPathTests.swift; sourceTree = ""; }; OBJ_10 /* Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decodable.swift; sourceTree = ""; }; - OBJ_11 /* NSManagedObject.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NSManagedObject.swift; sourceTree = ""; }; - OBJ_12 /* NSManagedObjectContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NSManagedObjectContext.swift; sourceTree = ""; }; OBJ_13 /* String.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = String.swift; sourceTree = ""; }; - OBJ_15 /* EntityMapping.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EntityMapping.swift; sourceTree = ""; }; OBJ_16 /* StringInitializable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringInitializable.swift; sourceTree = ""; }; OBJ_17 /* SLazeKit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SLazeKit.swift; sourceTree = ""; }; - OBJ_21 /* Model.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Model.swift; sourceTree = ""; }; OBJ_22 /* SLazeKitTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SLazeKitTests.swift; sourceTree = ""; }; OBJ_23 /* StringInitializableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringInitializableTests.swift; sourceTree = ""; }; OBJ_6 /* Package.swift */ = {isa = PBXFileReference; explicitFileType = sourcecode.swift; path = Package.swift; sourceTree = ""; }; @@ -98,7 +88,6 @@ OBJ_14 /* Protocols */ = { isa = PBXGroup; children = ( - OBJ_15 /* EntityMapping.swift */, OBJ_16 /* StringInitializable.swift */, 623922762002D8C30018982A /* LazeConfiguration.swift */, ); @@ -116,7 +105,6 @@ OBJ_19 /* SLazeKitTests */ = { isa = PBXGroup; children = ( - OBJ_20 /* Models */, OBJ_22 /* SLazeKitTests.swift */, OBJ_23 /* StringInitializableTests.swift */, 625B5F8E202288E700E72BCF /* StringPathTests.swift */, @@ -125,15 +113,6 @@ path = Tests/SLazeKitTests; sourceTree = SOURCE_ROOT; }; - OBJ_20 /* Models */ = { - isa = PBXGroup; - children = ( - OBJ_21 /* Model.swift */, - 625B23AB1FF34625001976C3 /* Object.swift */, - ); - path = Models; - sourceTree = ""; - }; OBJ_24 /* Products */ = { isa = PBXGroup; children = ( @@ -177,8 +156,6 @@ isa = PBXGroup; children = ( OBJ_10 /* Decodable.swift */, - OBJ_11 /* NSManagedObject.swift */, - OBJ_12 /* NSManagedObjectContext.swift */, OBJ_13 /* String.swift */, ); path = Extensions; @@ -286,9 +263,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 0; files = ( - OBJ_38 /* Model.swift in Sources */, OBJ_39 /* SLazeKitTests.swift in Sources */, - 625B23AD1FF3462B001976C3 /* Object.swift in Sources */, OBJ_40 /* StringInitializableTests.swift in Sources */, 625B5F8F202288E700E72BCF /* StringPathTests.swift in Sources */, ); @@ -299,11 +274,8 @@ buildActionMask = 0; files = ( OBJ_49 /* Decodable.swift in Sources */, - OBJ_50 /* NSManagedObject.swift in Sources */, 6239227E2002DF1A0018982A /* Laze.swift in Sources */, - OBJ_51 /* NSManagedObjectContext.swift in Sources */, OBJ_52 /* String.swift in Sources */, - OBJ_53 /* EntityMapping.swift in Sources */, OBJ_54 /* StringInitializable.swift in Sources */, 623922782002D8C30018982A /* LazeConfiguration.swift in Sources */, OBJ_55 /* SLazeKit.swift in Sources */, diff --git a/Sources/SLazeKit/Extensions/NSManagedObject.swift b/Sources/SLazeKit/Extensions/NSManagedObject.swift deleted file mode 100644 index 69be087..0000000 --- a/Sources/SLazeKit/Extensions/NSManagedObject.swift +++ /dev/null @@ -1,38 +0,0 @@ -import Foundation -import CoreData - -extension NSManagedObject { - /// String entity name - final public class var entityName: String? { - return NSStringFromClass(self).components(separatedBy: ".").last - } - /// Finds `NSManagedObject` by EntityAttribute parameters. - /// - /// - Parameters: - /// - context: Context on which fetch should be executed - /// - attributes: Entity attribute mapped by key - value - /// - Returns: Returns first object that meet the criteria specified by a given fetch request. - final public class func find(_ context: NSManagedObjectContext?, by attributes: EntityAttribute...) throws -> NSManagedObject? { - return try find(context, by: attributes.map {$0}) - } - - /// Finds `NSManagedObject` by EntityAttribute parameters. - /// - /// - Parameters: - /// - context: Context on which fetch should be executed - /// - attributes: Entity attribute mapped by key - value - /// - Returns: Returns first object that meet the criteria specified by a given fetch request. - final public class func find(_ context: NSManagedObjectContext?, by attributes: [EntityAttribute]) throws -> NSManagedObject? { - guard let name = entityName else { return nil } - let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: name) - var predicates: [NSPredicate] = [] - attributes.forEach({ - predicates.append(NSPredicate(format: "\($0.key) = %@", argumentArray: [$0.value])) - }) - if !predicates.isEmpty { - fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates) - } - fetchRequest.fetchLimit = 1 - return try context?.fetch(fetchRequest).first - } -} diff --git a/Sources/SLazeKit/Extensions/NSManagedObjectContext.swift b/Sources/SLazeKit/Extensions/NSManagedObjectContext.swift deleted file mode 100644 index bfdd393..0000000 --- a/Sources/SLazeKit/Extensions/NSManagedObjectContext.swift +++ /dev/null @@ -1,23 +0,0 @@ -import Foundation -import CoreData - -extension NSManagedObjectContext { - /// If the context has uncommitted changes, attempts to commit unsaved changes to registered objects to the context’s parent store. - public func commit() { - self.performAndWait { - if self.hasChanges { - do { - try save() - self.parent?.perform({ - if self.parent?.hasChanges == true { - self.parent?.commit() - self.parent?.refreshAllObjects() - } - }) - } catch { - print(error) - } - } - } - } -} diff --git a/Sources/SLazeKit/Protocols/EntityMapping.swift b/Sources/SLazeKit/Protocols/EntityMapping.swift deleted file mode 100644 index c3ec038..0000000 --- a/Sources/SLazeKit/Protocols/EntityMapping.swift +++ /dev/null @@ -1,61 +0,0 @@ -import Foundation -import CoreData - -/// Entity attribute alias for key, value tuple. -public typealias EntityAttribute = (key: String, value: Any) - -/// Mapping protocol. Required for request object serialization. -public protocol EntityMapping { - static var entityType: NSManagedObject.Type { get } - var idAttributes: [EntityAttribute]? { get } - func fillObject(with model: NSManagedObject) -} - -extension EntityMapping { - func map(_ context: NSManagedObjectContext) throws -> NSManagedObject? { - var model: NSManagedObject? = nil - var mapError: Error? - context.performAndWait { - do { - if let attribiutes = idAttributes { - model = try Self.entityType.find(context, by: attribiutes) ?? Self.entityType.init(context: context) - } else { - model = try findObject(context) ?? Self.entityType.init(context: context) - } - if let object = model { - fillObject(with: object) - } - } catch { - mapError = error - } - } - if let error = mapError { - throw error - } - return model - } - - private func findObject(_ context: NSManagedObjectContext?) throws -> NSManagedObject? { - return try Self.entityType.find(context, by: idAttributes ?? []) - } - - /// Serialized managed object from datastore by given attribiutes. To be more specific. If request is returning JSON with `EntityMapping` and given Encodable object conform to this protocol. It will be automaticaly updated in DataStore. This method featch this object. - /// - /// - Parameter context: Context on which fetch should be executed - /// - Returns: Serialized object from EntityMapping model - public func serialized(_ context: NSManagedObjectContext?) throws -> T? { - return (try Self.entityType.find(context, by: idAttributes ?? [])) as? T - } -} - -extension Array where Element: EntityMapping { - /// Serialized managed objects from datastore by given attribiutes. To be more specific. If request is returning JSON with `EntityMapping` and given Encodable object conform to this protocol. It will be automaticaly updated in DataStore. This method featch this objects. - /// - /// - Parameter context: Context on which fetch should be executed - /// - Returns: Array of serialized object from EntityMapping response type. - public func serialized(_ context: NSManagedObjectContext?) throws -> [T] { - return try compactMap({ try $0.serialized(context) }) - } -} - - diff --git a/Sources/SLazeKit/Protocols/LazeConfiguration.swift b/Sources/SLazeKit/Protocols/LazeConfiguration.swift index aa8fe7e..749ad21 100644 --- a/Sources/SLazeKit/Protocols/LazeConfiguration.swift +++ b/Sources/SLazeKit/Protocols/LazeConfiguration.swift @@ -6,7 +6,6 @@ // import Foundation -import CoreData /// LazeConfiguration protocol represents API configuration public protocol LazeConfiguration { @@ -30,10 +29,12 @@ public protocol LazeConfiguration { /// - Parameter request: `HTTPURLResponse` object to handle static func handle(_ response: HTTPURLResponse?) - /// Override of this method which will provide Context for bacground execution. + + /// Method dedicated to be use for synchronize object into persisten store /// - /// - Returns: NSManagedObjectContext - static func newBackgroundContext() -> NSManagedObjectContext? + /// - Parameter obj: encoded object + /// - Throws: error occured during the process + static func synchronize(_ obj: Any) } extension LazeConfiguration { @@ -44,5 +45,5 @@ extension LazeConfiguration { public static func setup(_ request: URLRequest) -> URLRequest { return request } public static func handle(_ response: HTTPURLResponse?) {} - public static func newBackgroundContext() -> NSManagedObjectContext? { return nil } + public static func synchronize(_ obj: Any) {} } diff --git a/Sources/SLazeKit/SLazeKit.swift b/Sources/SLazeKit/SLazeKit.swift index 2ebd3b6..99a7028 100644 --- a/Sources/SLazeKit/SLazeKit.swift +++ b/Sources/SLazeKit/SLazeKit.swift @@ -1,8 +1,4 @@ import Foundation -import CoreData - -public typealias EntityMappingCodable = EntityMapping & Codable -public typealias EntityMappingDecodable = EntityMapping & Decodable /// NetworkResponse tuple holding response `Data` and `HTTPURLResponse` public typealias NetworkResponse = (data: Data?, http: HTTPURLResponse?) @@ -12,7 +8,7 @@ public enum HTTPMethod { case GET, POST, PUT, PATCH, DELETE, COPY, HEAD, OPTIONS, LINK, UNLINK, PURGE, LOCK, UNLOCK, PROPFIND, VIEW } -/// SLazeKit is an easy to use restful collection of extensions and classes. Maps your rest api request into models and provides coredata serialization. +/// SLazeKit is an easy to use restful collection of extensions and classes. Maps your rest api request into models and provides serialization of your extension choice. public class SLazeKit { class func networkTask(request: URLRequest, handler: @escaping (_ response: NetworkResponse, _ error: Error?) -> Void) -> URLSessionDataTask? { guard let req = Config.setup(request) else { @@ -39,7 +35,7 @@ public class SLazeKit { if let data = data, error == nil { do { let object = try Config.decoder.decode(T.self, from: data) - try synchronize(object) + try Config.synchronize(object) handler((data, response as? HTTPURLResponse), object, nil) } catch { handler((data, response as? HTTPURLResponse), nil, error) @@ -181,17 +177,6 @@ public class SLazeKit { "queryItems":"\(queryItems ?? [])", "body":String(describing: body)]) } - - private class func synchronize(_ obj: Any) throws { - guard let context = Config.newBackgroundContext() else { return } - if let array = obj as? [EntityMapping] { - array.forEach({_ = try? $0.map(context)}) - } else { - guard let mapper = obj as? EntityMapping else { return } - _ = try mapper.map(context) - } - context.commit() - } } extension SLazeKit { diff --git a/Tests/SLazeKitTests/Models/Model.swift b/Tests/SLazeKitTests/Models/Model.swift deleted file mode 100644 index dd9576b..0000000 --- a/Tests/SLazeKitTests/Models/Model.swift +++ /dev/null @@ -1,170 +0,0 @@ -import Foundation -import SLazeKit -import CoreData - -class Model: NSManagedObject { - @nonobjc public class func fetchRequest() -> NSFetchRequest { - return NSFetchRequest(entityName: "Model") - } - - @NSManaged public var id: String - @NSManaged public var value: Double - @NSManaged public var name: String? - - /// Path pattern for our model API requests - public struct PathPattern { - static var model: String { return "/api/Models/:modelId" } - static var models: String { return "/api/Models" } - static var create: String { return "/api/Models/:modelId/create" } - static var delete: String { return "/api/Models/:modelId/delete" } - } - /// We are creating struct which represents Decodable response of API request - /// `EntityMappingDecodable` is required - public struct ModelResponse: EntityMappingDecodable { - var id: String - var value: Double - var name: String? - /// We need provide NSManagedObject type for our serialization. - public static var entityType: NSManagedObject.Type { - return Model.self - } - /// By providing id attributes our model are updated/created/serialized - public var idAttributes: [EntityAttribute]? { - return [ - ("id",id) - ] - } - - /// Fill CoreData object with our model response - public func fillObject(with model: NSManagedObject) { - guard let object = model as? Model else { return } - object.id = id - object.value = value - object.name = name - } - } - /// We could skip that and add `Encodable` to our ModelResponse. But to highlight it. We will create separate one for request purpose - public struct ModelRequest: Encodable { - var id: String - var value: Double - var name: String? - //Convenience initializer. - init(with model: Model) { - self.id = model.id - self.value = model.value - self.name = model.name - } - } - /// Create request. Called from SLazeKit. Response is not maped or serialized. - /// - /// - Parameters: - /// - model: CoreData model used to post request with body of ModelRequest - class func create(model: Model, success: @escaping (() ->()), failure: ((_ statusCode: Int, _ error: Error?) ->())? = nil) { - /// SLazeKit request are done i background. To handle response on main thread we need to dispatch it. - let _ = SLazeKit.post(path: PathPattern.create.patternToPath(with: ["modelId":model.id]), body: ModelRequest(with: model)) { (response, error) in - guard error == nil else { - DispatchQueue.main.async { failure?(response.http?.statusCode ?? -1,error) } - return - } - DispatchQueue.main.async { success() } - } - } - /// Another request example with out mapping or serialization. - /// - /// - Parameters: - /// - modelId: model id used to replace key string in path pattern. - /// - /// SLazeKit request are done i background. To handle response on main thread we need to dispatch it. - class func remove(for modelId: String, success: @escaping (() ->()), failure: ((_ statusCode: Int, _ error: Error?) ->())? = nil) { - let _ = SLazeKit.delete(path: PathPattern.delete.patternToPath(with: ["modelId":modelId])) { (response, error) in - guard error == nil else { - DispatchQueue.main.async { failure?(response.http?.statusCode ?? -1,error) } - return - } - DispatchQueue.main.async { success() } - } - } - /// `[ModelResponse]` Stands as a result type. Decodable provides generic requests. if Response model beside `Decodable` comforms to `EntityMapping` as well it will be serialized. - /// - /// [ModelResponse] Decodable type used to generate result type. - /// - ///Result is type of `[ModelResponse]` to return array of our CoreData models we need to serialize it. - ///`result?.serialized` will return `[Model]` - class func getFromServer(success: @escaping (([Model]?) ->()), failure: (() ->())? = nil) { - let _ = [ModelResponse].get(path: PathPattern.models.patternToPath()) { (response, result, error) in - guard error == nil else { - failure?() - return - } - var models: [Model]? = nil - do { - models = try result?.serialized(Default.newBackgroundContext()) - } catch { - print(error) - } - success(models) - } - } - /// In this example API request will decode single object of type ModelResponse instead of an array. - /// - ///Result of type `ModelResponse` to return CoreData model we need to serialize it. - /// - ///`result?.serialized` will return `Model` - class func getFromServer(for modelId: String, success: @escaping ((Model?) ->()), failure: (() ->())? = nil) { - let _ = ModelResponse.get(path: PathPattern.model.patternToPath(with: ["modelId":modelId])) { (response, result, error) in - guard error == nil else { - failure?() - return - } - var models: Model? = nil - do { - models = try result?.serialized(Default.newBackgroundContext()) - } catch { - print(error) - } - success(models) - } - } - - /// In this example API request will decode single object of type ModelResponse instead of an array. - /// - ///Result of type `ModelResponse` to return CoreData model we need to serialize it. - /// - ///`result?.serialized` will return `Model` - class func getFromOtherServer(for modelId: String, success: @escaping ((Model?) ->()), failure: (() ->())? = nil) { - class NoneDefault: LazeConfiguration { - static var basePath: String? { return "www.yourdomain.com" } - static var basePort: Int? { return 8765 } - static var decoder: JSONDecoder { return JSONDecoder() } - static var urlSession: URLSession { return URLSession.shared } - - static func setup(_ request: URLRequest) -> URLRequest { - var request: URLRequest = request - request.setValue("Your token", forHTTPHeaderField: "X-Access-Token") - request.setValue("application/json", forHTTPHeaderField: "Content-Type") - return request - } - - static func handle(_ response: HTTPURLResponse?) { - if response?.statusCode == 401 { - print("unauthorised") - } - } - - public static func newBackgroundContext() -> NSManagedObjectContext? { return NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) } - } - let _ = Laze.get(path: PathPattern.model.patternToPath(with: ["modelId":modelId])) { (response, result, error) in - guard error == nil else { - failure?() - return - } - var models: Model? = nil - do { - models = try result?.serialized(Default.newBackgroundContext()) - } catch { - print(error) - } - success(models) - } - } -} diff --git a/Tests/SLazeKitTests/Models/Object.swift b/Tests/SLazeKitTests/Models/Object.swift deleted file mode 100644 index 8a0188c..0000000 --- a/Tests/SLazeKitTests/Models/Object.swift +++ /dev/null @@ -1,55 +0,0 @@ -import Foundation -import SLazeKit -import CoreData - -class Object: NSManagedObject { - @nonobjc public class func fetchRequest() -> NSFetchRequest { - return NSFetchRequest(entityName: "Object") - } - - @NSManaged public var id: String - @NSManaged public var value: Double - @NSManaged public var name: String? - - /// Path pattern for our model API requests - public struct PathPattern { - static var model: String { return "/api/Objects/:modelId" } - static var models: String { return "/api/Objects" } - static var create: String { return "/api/Objects/:modelId/create" } - static var delete: String { return "/api/Objects/:modelId/delete" } - } - /// We are creating struct which represents Codable object of our API request - /// `EntityMappingCodable` is required - public struct ObjectRestful: EntityMappingCodable { - var id: String - var value: Double - var name: String? - /// We need provide NSManagedObject type for our serialization. - public static var entityType: NSManagedObject.Type { - return Object.self - } - /// By providing id attributes our model are updated/created/serialized - public var idAttributes: [EntityAttribute]? { - return [ - ("id",id) - ] - } - /// init ObjectRestful with our Object clss - /// - /// - Parameter model: model of our Object class - init(with model: Object) { - self.id = model.id - self.value = model.value - self.name = model.name - } - - /// Fill CoreData object with our model response - public func fillObject(with model: NSManagedObject) { - guard let object = model as? Object else { return } - object.id = id - object.value = value - object.name = name - } - } -} -