I'd like to use a ResponseTransformer (or a series of them) to automatically map my object model classes to the responses coming back from a Siesta service so that my Siesta resources are instances of my model classes. I have a working implementation for one class, but I'd like to know if there is a safer, smarter or more efficient way to do this before I build a separate ResponseTransformer for each type of resource (model).
Here is a sample model class:
import SwiftyJSON
class Challenge {
var id:String?
var name:String?
init(fromDictionary:JSON) {
if let challengeId = fromDictionary["id"].int {
self.id = String(challengeId)
}
self.name = fromDictionary["name"].string
}
}
extension Challenge {
class func parseChallengeList(fromJSON:JSON) -> [Challenge] {
var list = [Challenge]()
switch fromJSON.type {
case .Array:
for itemDictionary in fromJSON.array! {
let item = Challenge(fromDictionary: itemDictionary)
list.append(item)
}
case .Dictionary:
list.append(Challenge(fromDictionary: fromJSON))
default: break
}
return list
}
}
And here is the ResponseTransformer I built to map the response from any endpoint that returns either a collection of this model type or a single instance of this model type:
public func ChallengeListTransformer(transformErrors: Bool = true) -> ResponseTransformer {
return ResponseContentTransformer(transformErrors: transformErrors)
{
(content: NSJSONConvertible, entity: Entity) throws -> [Challenge] in
let itemJSON = JSON(content)
return Challenge.parseChallengeList(itemJSON)
}
}
And, finally, here is the URL Pattern mapping I am doing when I configure the Siesta service:
class _GFSFAPI: Service {
...
configure("/Challenge/*") { $0.config.responseTransformers.add(ChallengeListTransformer()) }
}
I am planning to build a separate ResponseTransformer for each model type, and then individually map each URL Pattern to that transformer. Is that the best approach? By the way, I am super excited about the new Siesta framework. I love the idea of a resource-oriented REST Networking Library.