1

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?

Uncommon
  • 3,323
  • 2
  • 18
  • 36
  • 1
    The reason this doesn’t work is that as of beta 8, later `configureTransformer` calls replace earlier ones by default, so the first String→String transformer never even gets applied. If you configured that String→String block for `**/properties/*`, it would override the `**` one. But as your answer notes, `Content-type` is the better way. – Paul Cantrell Jul 21 '16 at 21:15

1 Answers1

1

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" ])
}
Uncommon
  • 3,323
  • 2
  • 18
  • 36