Search code examples
siesta-swift

Response transformer exceptions


With the service I'm working with, most of the responses are in XML, but a few are plain text. What's the best way to set that up?

Currently I have this:

// Root should return plain text, don't try to transform it
configureTransformer("/") { (content: String, entity) -> String? in
  return content
}
// Most data is XML
configureTransformer("**") { (content: NSData, entity) -> NSXMLDocument? in
  return try? NSXMLDocument(data: content, options: 0)
}
configureTransformer("**/properties/*") {
  (content: NSData, entity) -> String? in
  return String(data: content, encoding: NSUTF8StringEncoding)
}

..but when I query the root URL, which will be plain text, I get an error because the NSData -> NSXMLDocument transformer can't be applied.

Edit: Maybe what I really want is to apply the XML transformer when the content-type is application/xml. Is there a way to do that?


Solution

  • Based on what I see in Service.init(), I did this, and it's working pretty well:

    func XMLResponseTransformer(
        transformErrors: Bool = true) -> Siesta.ResponseTransformer
    {
      return Siesta.ResponseContentTransformer(transformErrors: transformErrors) {
        (content: NSData, entity: Siesta.Entity) throws -> NSXMLDocument in
        return try NSXMLDocument(data: content, options: 0)
      }
    }
    
    configure(description: "xml") {
      $0.config.pipeline[.parsing].add(XMLResponseTransformer(),
                                       contentTypes: [ "*/xml" ])
    }