Skip to content

Instantly share code, notes, and snippets.

@aal89
Created September 12, 2017 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aal89/4eff536f7f2ae6ead65fd2d4fec23638 to your computer and use it in GitHub Desktop.
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>
// 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
}
@aal89
Copy link
Author

aal89 commented Mar 22, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment