Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make YAMLDecoder compliant to TopLevelDecoder to be used with Combine.decode #261

Closed
marcblanchet opened this issue Jul 3, 2020 · 5 comments

Comments

@marcblanchet
Copy link

would be cool to chain with Combine .decode(type: ..., decoder: YAMLDecoder()) but YAMLDecoder is not compliant with protocol TopLevelDecoder. XMLCoder does it and it is really useful

@jpsim
Copy link
Owner

jpsim commented Jul 4, 2020

Thanks for the suggestion! In the meantime, you should be able to add the conformance in your own code:

extension YAMLDecoder: TopLevelDecoder {
    public typealias Input = String

    public func decode<T>(_ type: T.Type, from: String) throws -> T where T : Decodable {
        try self.decode(type, from: from, userInfo: [:])
    }
}

@jpsim
Copy link
Owner

jpsim commented Jul 4, 2020

Started a PR tracking the work left to do here: #262

@marcblanchet
Copy link
Author

marcblanchet commented Jul 4, 2020

suggested code seems halfway. If I do:

extension URLSession {
enum SessionErrorHTTP: Error {
    case statusCode(HTTPURLResponse)
  }
func dataTaskPublisher<T: Decodable>(for request: URLRequest) -> AnyPublisher<T, Error> {
    return self.dataTaskPublisher(for: request)
      .tryMap({ (data, response) -> Data in
        if let response = response as? HTTPURLResponse,
          (200..<300).contains(response.statusCode) == false {
          throw SessionErrorHTTP.statusCode(response)
        }
        return data
      })
      .decode(type: T.self, decoder: JSONDecoder())
      .eraseToAnyPublisher()
  }
}

I can replace JSONDecoder() above with XMLCoder or CSVDecoder, but not yet YAMLDecoder (even with your suggestion). Some piece is missing.

@jpsim
Copy link
Owner

jpsim commented Jul 4, 2020

With my provided code, you need to give the decoder a String instead of Data.

@jpsim jpsim closed this as completed Jul 7, 2020
@marcblanchet
Copy link
Author

thanks a bunch! will test it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants