Skip to content

Instantly share code, notes, and snippets.

@Andrea-Scuderi
Created August 1, 2019 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrea-Scuderi/2ff5ce8c284f0e3abdfb71823384edf4 to your computer and use it in GitHub Desktop.
Save Andrea-Scuderi/2ff5ce8c284f0e3abdfb71823384edf4 to your computer and use it in GitHub Desktop.
Part 6
// Use of the dataTaskPublisher API to implement Publisher with the decoded data
struct Token: Codable {
let string: String
}
// We'll use the following function to validate our dataTaskPublisher output in the pipeline
func validate(_ data: Data, _ response: URLResponse) throws -> Data {
guard let httpResponse = response as? HTTPURLResponse else {
throw APIError.invalidResponse
}
guard (200..<300).contains(httpResponse.statusCode) else {
throw APIError.statusCode(httpResponse.statusCode)
}
return data
}
func create(user: User) -> AnyPublisher<CreateUserResponse, Error>? {
return try? postUser(user: user)
.tryMap{ try validate($0.data, $0.response) }
.decode(type: CreateUserResponse.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
func login(email: String, password: String) -> AnyPublisher<Token, Error> {
return postLogin(email: email, password: password)
.tryMap{ try validate($0.data, $0.response) }
.decode(type: Token.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
func postTodo(authToken: String, todo: Todo) -> AnyPublisher<Todo, Error> {
return postTodo(authToken: authToken, body: todo)
.tryMap{ try validate($0.data, $0.response) }
.decode(type: Todo.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
func getTodo(authToken: String) -> AnyPublisher<[Todo], Error> {
return getTodo(authToken: authToken)
.tryMap{ try validate($0.data, $0.response) }
.decode(type: [Todo].self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
func deleteTodo(authToken: String, id: Int) -> AnyPublisher<Todo, Error> {
return deleteTodo(authToken: authToken, id: id)
.tryMap{ try validate($0.data, $0.response) }
.decode(type: Todo.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment