Share
Embed
Functional Networking
This talk presents a set of refactorings that will help make your Swift networking code more functional. It also features a tool, Bow OpenAPI, that generates your network layer from a Swagger/OpenAPI specification file into a Swift Package.
Tomás Ruiz-López
February 03, 2020
Transcript
51 slides
-
openapi: "3.0.0" info: title: Blogging platform version: "1.0.0" paths: /articles:
get: tags: - Article operationId: getArticlesWithTag parameters: - name: tag in: query required: true schema: type: string responses: '200': description: The list of articles for the specified tag content: application/json: schema: $ref: '#/components/schemas/Articles' -
openapi: "3.0.0" info: title: Blogging platform version: "1.0.0" paths: /articles:
get: tags: - Article operationId: getArticlesWithTag parameters: - name: tag in: query required: true schema: type: string responses: '200': description: The list of articles for the specified tag content: application/json: schema: $ref: '#/components/schemas/Articles' -
openapi: "3.0.0" info: title: Blogging platform version: "1.0.0" paths: /articles:
get: tags: - Article operationId: getArticlesWithTag parameters: - name: tag in: query required: true schema: type: string responses: '200': description: The list of articles for the specified tag content: application/json: schema: $ref: '#/components/schemas/Articles' -
openapi: "3.0.0" info: title: Blogging platform version: "1.0.0" paths: /articles:
get: tags: - Article operationId: getArticlesWithTag parameters: - name: tag in: query required: true schema: type: string responses: '200': description: The list of articles for the specified tag content: application/json: schema: $ref: '#/components/schemas/Articles' -
components: schemas: Articles: type: array items: $ref: '#/components/schemas/Article' Article: type:
object required: - id - title properties: id: type: integer name: type: string -
components: schemas: Articles: type: array items: $ref: '#/components/schemas/Article' Article: type:
object required: - id - title properties: id: type: integer name: type: string -
components: schemas: Articles: type: array items: $ref: '#/components/schemas/Article' Article: type:
object required: - id - title properties: id: type: integer name: type: string -
func getArticles(withTag tag: String, callback: @escaping (Result<[Article], Error>) !-> Void)
{ let path = basePath + "/articles" var components = URLComponents(string: path) components!?.queryItems = [URLQueryItem(name: "tag", value: tag)] guard let url = components!?.url else { callback(.failure(NetworkError.malformedURL)) return } var request = URLRequest(url: url) request.httpMethod = "GET" headers.forEach { header in request.setValue(header.value, forHTTPHeaderField: header.key) } send(request: request, callback: callback) } -
func getArticles(withTag tag: String, callback: @escaping (Result<[Article], Error>) !-> Void)
{ let path = basePath + "/articles" var components = URLComponents(string: path) components!?.queryItems = [URLQueryItem(name: "tag", value: tag)] guard let url = components!?.url else { callback(.failure(NetworkError.malformedURL)) return } var request = URLRequest(url: url) request.httpMethod = "GET" headers.forEach { header in request.setValue(header.value, forHTTPHeaderField: header.key) } send(request: request, callback: callback) } -
func getArticles(withTag tag: String, callback: @escaping (Result<[Article], Error>) !-> Void)
{ let path = basePath + "/articles" var components = URLComponents(string: path) components!?.queryItems = [URLQueryItem(name: "tag", value: tag)] guard let url = components!?.url else { callback(.failure(NetworkError.malformedURL)) return } var request = URLRequest(url: url) request.httpMethod = "GET" headers.forEach { header in request.setValue(header.value, forHTTPHeaderField: header.key) } send(request: request, callback: callback) } -
func getArticles(withTag tag: String, callback: @escaping (Result<[Article], Error>) !-> Void)
{ let path = basePath + "/articles" var components = URLComponents(string: path) components!?.queryItems = [URLQueryItem(name: "tag", value: tag)] guard let url = components!?.url else { callback(.failure(NetworkError.malformedURL)) return } var request = URLRequest(url: url) request.httpMethod = "GET" headers.forEach { header in request.setValue(header.value, forHTTPHeaderField: header.key) } send(request: request, callback: callback) } -
func send(request: URLRequest, callback: @escaping (Result<[Article], Error>) !-> Void) {
URLSession.shared.dataTask(with: request) { data, response, error in if let data = data, let response = response as? HTTPURLResponse { switch response.statusCode { case 200 !!..< 300: if let decoded = try? JSONDecoder().decode([Article].self, from: data) { callback(.success(decoded)) } else { callback(.failure(NetworkError.notDecodable)) } default: callback(.failure(NetworkError.malformedURL)) } } else if let error = error { callback(.failure(error)) } }.resume() } -
func send(request: URLRequest, callback: @escaping (Result<[Article], Error>) !-> Void) {
URLSession.shared.dataTask(with: request) { data, response, error in if let data = data, let response = response as? HTTPURLResponse { switch response.statusCode { case 200 !!..< 300: if let decoded = try? JSONDecoder().decode([Article].self, from: data) { callback(.success(decoded)) } else { callback(.failure(NetworkError.notDecodable)) } default: callback(.failure(NetworkError.malformedURL)) } } else if let error = error { callback(.failure(error)) } }.resume() } -
func send(request: URLRequest, callback: @escaping (Result<[Article], Error>) !-> Void) {
URLSession.shared.dataTask(with: request) { data, response, error in if let data = data, let response = response as? HTTPURLResponse { switch response.statusCode { case 200 !!..< 300: if let decoded = try? JSONDecoder().decode([Article].self, from: data) { callback(.success(decoded)) } else { callback(.failure(NetworkError.notDecodable)) } default: callback(.failure(NetworkError.malformedURL)) } } else if let error = error { callback(.failure(error)) } }.resume() } -
func send(request: URLRequest, callback: @escaping (Result<[Article], Error>) !-> Void) {
URLSession.shared.dataTask(with: request) { data, response, error in if let data = data, let response = response as? HTTPURLResponse { switch response.statusCode { case 200 !!..< 300: if let decoded = try? JSONDecoder().decode([Article].self, from: data) { callback(.success(decoded)) } else { callback(.failure(NetworkError.notDecodable)) } default: callback(.failure(NetworkError.malformedURL)) } } else if let error = error { callback(.failure(error)) } }.resume() } -
func send(request: URLRequest, callback: @escaping (Result<[Article], Error>) !-> Void) {
URLSession.shared.dataTask(with: request) { data, response, error in if let data = data, let response = response as? HTTPURLResponse { switch response.statusCode { case 200 !!..< 300: if let decoded = try? JSONDecoder().decode([Article].self, from: data) { callback(.success(decoded)) } else { callback(.failure(NetworkError.notDecodable)) } default: callback(.failure(NetworkError.malformedURL)) } } else if let error = error { callback(.failure(error)) } }.resume() } -
func send(request: URLRequest, callback: @escaping (Result<[Article], Error>) !-> Void) {
URLSession.shared.dataTask(with: request) { data, response, error in if let data = data, let response = response as? HTTPURLResponse { switch response.statusCode { case 200 !!..< 300: if let decoded = try? JSONDecoder().decode([Article].self, from: data) { callback(.success(decoded)) } else { callback(.failure(NetworkError.notDecodable)) } default: callback(.failure(NetworkError.malformedURL)) } } else if let error = error { callback(.failure(error)) } }.resume() } -
func send(request: URLRequest, callback: @escaping (Result<[Article], Error>) !-> Void) {
URLSession.shared.dataTask(with: request) { data, response, error in if let data = data, let response = response as? HTTPURLResponse { switch response.statusCode { case 200 !!..< 300: if let decoded = try? JSONDecoder().decode([Article].self, from: data) { callback(.success(decoded)) } else { callback(.failure(NetworkError.notDecodable)) } default: callback(.failure(NetworkError.malformedURL)) } } else if let error = error { callback(.failure(error)) } }.resume() } Insufficient abstraction -
func send<T: Decodable>(request: URLRequest, callback: @escaping (Result<T, Error>) !-> Void)
{ URLSession.shared.dataTask(with: request) { data, response, error in if let data = data, let response = response as? HTTPURLResponse { switch response.statusCode { case 200 !!..< 300: if let decoded = try? JSONDecoder().decode(T.self, from: data) { callback(.success(decoded)) } else { callback(.failure(NetworkError.notDecodable)) } default: callback(.failure(NetworkError.malformedURL)) } } else if let error = error { callback(.failure(error)) } }.resume() } Insufficient abstraction Parametric polymorphism -
func dataTaskADT(with request: URLRequest, completion: @escaping (Either<Error, (Data, URLResponse)>) !->
Void) Illegal states Algebraic Data Types -
func dataTaskADT(with request: URLRequest, completion: @escaping (Either<Error, (Data, URLResponse)>) !->
Void) Callback-based communication & Side-effects -
func dataTaskIO(with request: URLRequest) !-> IO<Error, (Data, URLResponse)> Callbacks &
Side-Effects Suspension -
extension URLSession { func dataTaskIO(with request: URLRequest) !-> IO<Error, (Data,
URLResponse)> { IO.async { callback in self.dataTask(with: request) { data, response, error in if let data = data, let response = response { callback(.right((data, response))) } else if let error = error { callback(.left(error)) } }.resume() }^ } } -
func send<T: Decodable>(request: URLRequest) !-> IO<Error, T> { URLSession.shared.dataTaskIO(with: request)
.flatMap { response, data in guard let response = response as? HTTPURLResponse else { return IO.raiseError(NetworkError.malformedURL) } switch response.statusCode { case 200 !!..< 300: return JSONDecoder().safeDecode(T.self, from: data) default: return IO.raiseError(NetworkError.malformedURL) } }^ } Global dependencies -
func send<T: Decodable>(request: URLRequest, session: URLSession, decoder: SafeDecoder) !-> IO<Error,
T> Global dependencies Explicit dependencies -
func send<T: Decodable>(request: URLRequest, config: APIConfig) !-> IO<Error, T> Global
dependencies Explicit dependencies -
func send<T: Decodable>(request: URLRequest) !-> (APIConfig) !-> IO<Error, T> Global
dependencies Explicit dependencies -
func send<T: Decodable>(request: URLRequest) !-> EnvIO<APIConfig, Error, T> { EnvIO
{ config in config.session.dataTaskIO(with: request) .flatMap { response, data in guard let response = response as? HTTPURLResponse else { return IO.raiseError(NetworkError.malformedURL) } switch response.statusCode { case 200 !!..< 300: return config.decoder.safeDecode(T.self, from: data) default: return IO.raiseError(NetworkError.malformedURL) } }^ } } Global dependencies Environmental Effects -
brew tap bow-swift/bow brew install bow-openapi bow-openapi "#name MyAPI "#schema
Swagger.json "#output ./MyAPI Install Run -
let config = API.Config(basePath: “https:!//url-to-my-server.com") let articles = try? articlesRequest.provide(config).unsafeRunSync()
articlesRequest.provide(config).unsafeRunAsync { either in either.fold({ httpError in !/* !!... !*/ }, { articles in !/* !!... !*/ }) } Running a request -
import MyAPITest func testEmptyResponse() { let successConfig = API.Config(basePath: "https:!//url-to-my-server.com")
.stub(json: "[]", code: 200) let expected = [] assert(API.article.getArticles(), withConfig: successConfig, succeeds: expected, "An empty array was expected") } func testContentResponse() { let successConfig = API.Config(basePath: "https:!//url-to-my-server.com") .stub(contentsOfFile: fileURL, code: 200) let expected = [ Article(identifier: 1234, title: "Intro to Bow OpenAPI") ] assert(API.article.getArticles(), withConfig: successConfig, succeeds: expected, "An array with a single element was expected") } Testing a request -
import MyAPITest func testEmptyResponse() { let successConfig = API.Config(basePath: "https:!//url-to-my-server.com")
.stub(json: "[]", code: 200) let expected = [] assert(API.article.getArticles(), withConfig: successConfig, succeeds: expected, "An empty array was expected") } func testContentResponse() { let successConfig = API.Config(basePath: "https:!//url-to-my-server.com") .stub(contentsOfFile: fileURL, code: 200) let expected = [ Article(identifier: 1234, title: "Intro to Bow OpenAPI") ] assert(API.article.getArticles(), withConfig: successConfig, succeeds: expected, "An array with a single element was expected") } Testing a request -
import MyAPITest func testEmptyResponse() { let successConfig = API.Config(basePath: "https:!//url-to-my-server.com")
.stub(json: "[]", code: 200) let expected = [] assert(API.article.getArticles(), withConfig: successConfig, succeeds: expected, "An empty array was expected") } func testContentResponse() { let successConfig = API.Config(basePath: "https:!//url-to-my-server.com") .stub(contentsOfFile: fileURL, code: 200) let expected = [ Article(identifier: 1234, title: "Intro to Bow OpenAPI") ] assert(API.article.getArticles(), withConfig: successConfig, succeeds: expected, "An array with a single element was expected") } Testing a request -
Bow vs. Combine Works in earlier versions of iOS and
macOS Lazyness guarantees referential transparency -
binding( user !<- API.user.getMyProfile(), articles !<- API.article.getArticles(withTag: "featured"), home !<-
makeHome(for: user.get, with: articles.get), yield: home.get) Bow vs. Combine Convenient imperative-style syntax