Last active
August 1, 2019 09:57
-
-
Save Andrea-Scuderi/9f3e5637fb48d15d607d5666790a04b6 to your computer and use it in GitHub Desktop.
Vapor API client for auth-template: Create User - part 2
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
import Combine | |
// With Combine we return a DataTaskPublisher instead of using the completion handler of the DataTask | |
func postUser(user: User) throws -> URLSession.DataTaskPublisher { | |
let headers = [ | |
"Content-Type": "application/json", | |
"cache-control": "no-cache", | |
] | |
let encoder = JSONEncoder() | |
guard let postData = try? encoder.encode(user) else { | |
throw APIError.invalidBody | |
} | |
guard let url = URL(string: baseURL + "/users" ) else { | |
throw APIError.invalidEndpoint | |
} | |
var request = URLRequest(url: url, | |
cachePolicy: .useProtocolCachePolicy, | |
timeoutInterval: 10.0) | |
request.httpMethod = "POST" | |
request.allHTTPHeaderFields = headers | |
request.httpBody = postData as Data | |
let session = URLSession.shared | |
return session.dataTaskPublisher(for: request) | |
} | |
// Basic usage of the API client with dataTaskPublisher | |
// Create a DataTaskPublisher | |
let postUserPublisher = try? postUser(user: User(id:3)) | |
// Use the sink Subscriber to complete the Publisher -> Subscriber pipeline | |
let cancellable = postUserPublisher?.sink(receiveCompletion: { (completion) in | |
switch completion { | |
case .failure(let error): | |
print(error) | |
case .finished: | |
print("DONE - postUserPublisher") | |
} | |
}, receiveValue: { (data, response) in | |
if let string = String(data: data, encoding: .utf8) { | |
print(string) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment