Search code examples
swiftpipelinesiesta-swift

Swift Siesta redirect response to failure


Is possible using Siesta pipeline, receive a success response, parsing it, and depending of the return, redirect it to a failure response?

My server response many times return a HTTP 200, but with a error message/flag.


Solution

  • If by “redirect” you mean “transform an HTTP success into a Siesta error,” then yes, this is possible. The pipeline can arbitrarily transform successes into errors and vice versa.

    Write a ResponseTransformer that unwraps the .success case, checks whether the error flags are set (whatever they are), and if so returns a newly constructed .failure.

    For example, here is a sketch of a transformer that checks for an X-My-API-Error header on a 200, and if it is present returns an error:

    struct APIErrorHandler: ResponseTransformer {
      func process(_ response: Response) -> Response {
        switch response {
          case .success(let entity):
            if let errorMessage = entity.header(forKey: "X-My-API-Error") {
              return logTransformation(
                .failure(Error(userMessage: errorMessage, cause: MyAPIError(), entity: entity)))
            }
            return response
    
          case .failure:
            return response  // no change
        }
      }
    }
    

    Configure it as follows:

    service.configure {
      $0.pipeline[.cleanup].add(APIErrorHandler())
    }
    

    You might also find it helpful to study the transformer from the example project that turn a 404 into a successful response with false for the content, and the one that overrides Siesta’s default error message with a server-provided one.