Last active
August 1, 2019 14:00
-
-
Save Andrea-Scuderi/b20e96cc1950c9d60fe91da9e1122722 to your computer and use it in GitHub Desktop.
Vapor API client for auth-template: Create User
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 Cocoa | |
import Foundation | |
let baseURL = "http://localhost:8080" | |
enum APIError: Error { | |
case invalidBody | |
case invalidEndpoint | |
case invalidURL | |
case emptyData | |
case invalidJSON | |
case invalidResponse | |
case statusCode(Int) | |
} | |
struct User: Codable { | |
let name: String | |
let email: String | |
let password: String | |
let verifyPassword: String | |
} | |
// We'll use this extension to quickly generate some user for our requests | |
extension User { | |
init(id: Int) { | |
self.name = "user\(id)" | |
self.email = "user\(id)@example.com" | |
self.password = "password\(id)" | |
self.verifyPassword = "password\(id)" | |
} | |
} | |
// Basic API client using dataTask | |
// From now on, we'll use the suffix OLD to indicate the API Client implemented with dataTask | |
func createUserOLD(user: User, completion: @escaping (Data?, URLResponse?, Error?) -> Void) { | |
let headers = [ | |
"Content-Type": "application/json", | |
"cache-control": "no-cache", | |
] | |
let encoder = JSONEncoder() | |
guard let postData = try? encoder.encode(user) else { | |
completion(nil,nil, APIError.invalidBody) | |
return | |
} | |
guard let url = URL(string: baseURL + "/users" ) else { | |
completion(nil,nil, APIError.invalidEndpoint) | |
return | |
} | |
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 | |
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: completion) | |
dataTask.resume() | |
} | |
// Basic usage of the dataTask client | |
createUserOLD(user: User(id:2)) { (data, response, error) in | |
if let data = data, | |
let string = String(data: data, encoding: .utf8) { | |
print(string) | |
} else { | |
print(" - No data") | |
} | |
//print(response ?? "") | |
print(error ?? "") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment