Last active
August 1, 2019 09:58
-
-
Save Andrea-Scuderi/11c05181b8a33343a0925e719e99a4ae to your computer and use it in GitHub Desktop.
Vapor API client for auth-template: Create User - part 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In a real world App we want to decode our JSON data response into a Codable Object | |
struct CreateUserResponse: Codable { | |
let id: Int | |
let email: String | |
let name: String | |
} | |
// Decoding CreateUserResponse inside a DataTask API client | |
createUserOLD(user: User(id: 4)) { (data, response, error) in | |
let decoder = JSONDecoder() | |
do { | |
if let data = data { | |
let response = try decoder.decode(CreateUserResponse.self, from: data) | |
print(response) | |
} else { | |
print(APIError.emptyData) | |
} | |
} catch (let error) { | |
print(error) | |
} | |
} | |
// Decoding CreateUserResponse inside the pipeline | |
// Note: For simplicity, we are not considering the response.statusCode | |
let postUser5Publisher = try? postUser(user: User(id: 5)) | |
let decoder = JSONDecoder() | |
let cancellable2 = postUser5Publisher? | |
.map { $0.data } | |
.decode(type: CreateUserResponse.self, decoder: decoder) | |
.sink(receiveCompletion: { (completion) in | |
switch completion { | |
case .failure(let error): | |
print(error) | |
case .finished: | |
print("DONE - postUser5Publisher") | |
} | |
}, receiveValue: { user in | |
print(user) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment