Created
September 12, 2017 10:28
-
-
Save aal89/4eff536f7f2ae6ead65fd2d4fec23638 to your computer and use it in GitHub Desktop.
Easy and small extension to increase usability of Moya & ObjectMapper for backend abstraction layers. Easily turn a http response into an new-ed, mapped <T: Mappable>
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
// MARK: | |
// usage example: | |
// let test: Hello = "{\"hello\": \"world\"}".conform(Hello()) | |
// The class Hello() should extend Mappable, also see ObjectMapper docs. | |
import ObjectMapper | |
extension String { | |
func conform<T: Mappable>(_ model: T) -> T { | |
return Mapper<T>().map(JSONString: self)! | |
} | |
} | |
// MARK: | |
// the following function should be declared in a base model class which handles basic Moya requests. | |
// this handle function will then a json mapped String object on which later you can call conform. | |
// | |
// usage example: | |
// let test = try BaseModel.toHandle(moya: result).conform(Hello()) | |
// | |
// print(test.hello) | |
// world | |
import Moya | |
class func toHandle(moya r: Result<Moya.Response, Moya.MoyaError>) throws -> String { | |
let demat = try r.dematerialize() | |
let responseJson = try demat.mapString() | |
let resp = demat.response as! HTTPURLResponse | |
if resp.statusCode != 200 && resp.statusCode != 204 { | |
throw MoyaError.statusCode(demat) | |
} | |
return responseJson | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey! It's Swift 4 Codable!
Do this now: https://www.raywenderlich.com/172145/encoding-decoding-and-serialization-in-swift-4