Skip to content

Instantly share code, notes, and snippets.

@Andrea-Scuderi
Last active August 1, 2019 09:57
Show Gist options
  • Save Andrea-Scuderi/9f3e5637fb48d15d607d5666790a04b6 to your computer and use it in GitHub Desktop.
Save Andrea-Scuderi/9f3e5637fb48d15d607d5666790a04b6 to your computer and use it in GitHub Desktop.
Vapor API client for auth-template: Create User - part 2
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