SlideShare a Scribd company logo
Modern Networking
with Swish
@jakecraige
ArgoFunctional JSON parsing library
Swish
Nothing but net(working)
Setting up a Model with Argo
struct Comment {
let id: Int
let text: String
let user: String
}
extension Comment: Decodable {
// Assume: { "id": 1, "commentText": "Hello world", "user": "ralph" }
static func decode(json: JSON) -> Decoded<Comment> {
return curry(Comment.init)
<^> json <| "id"
<*> json <| "commentText"
<*> json <| "user"
}
}
Building a GET Request
struct CommentRequest: Request {
typealias ResponseObject = Comment
let id: Int
func build() -> NSURLRequest {
let url = NSURL(
string: "https://www.example.com/comments/(id)"
)!
return NSURLRequest(URL: url)
}
}
Executing the GET Request
let request = CommentRequest(id: 1)
APIClient().performRequest(request) { result in
switch result { // Result<Comment, SwishError>
case let .Success(comment):
print("Here's the comment: (comment)")
case let .Failure(error):
print("Oh no, an error: (error)")
}
}
// => Comment(id: 1, text: "Hi", user: "ralph")
GETs are easy.
How about POSTs?
Building a POST Request
struct CreateCommentRequest: Request {
typealias ResponseObject = Comment
let text: String
let user: String
var jsonPayload: [String: AnyObject] {
return ["text": text, "user": user]
}
func build() -> NSURLRequest {
// ...
}
}
Building a POST Request
struct CreateCommentRequest: Request {
// ...
func build() -> NSURLRequest {
let url = NSURL(string: "https://www.example.com/comments")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.jsonPayload = jsonPayload
return request
}
}
Executing the POST Request
let request = CreateCommentRequest(text: "Hola", user: "ralph")
APIClient().performRequest(request) { result in
switch result { // Result<Comment, SwishError>
case let .Success(comment):
print("Here's the comment: (value)")
case let .Failure(error):
print("Oh no, an error: (error)")
}
}
// => Comment(id: 2, text: "Hola", user: "ralph")
! "
Let's break it down !
Argo's Decodable
protocol Decodable {
associatedtype DecodedType = Self
static func decode(_ json: JSON) -> Decoded<DecodedType>
}
Argo's Decodable
protocol Decodable {
associatedtype DecodedType = Self
static func decode(_ json: JSON) -> Decoded<DecodedType>
}
extension Comment: Decodable {
static func decode(json: JSON) -> Decoded<Comment> {
return curry(Comment.init)
<^> json <| "id"
<*> json <| "commentText"
<*> json <| "user"
}
}
Swish's Request
protocol Parser {
associatedtype Representation
static func parse(j: AnyObject) -> Result<Representation, SwishError>
}
protocol Request {
associatedtype ResponseObject
associatedtype ResponseParser: Parser = JSON
func build() -> NSURLRequest
func parse(j: ResponseParser.Representation)
-> Result<ResponseObject, SwishError>
}
Swish's Request
protocol Request {
associatedtype ResponseObject
associatedtype ResponseParser: Parser = JSON
func build() -> NSURLRequest
func parse(j: ResponseParser.Representation) -> Result<ResponseObject, SwishError>
}
struct CommentRequest: Request {
typealias ResponseObject = Comment
let id: Int
func build() -> NSURLRequest {
let url = NSURL(string: "https://www.example.com/comments/(id)")!
return NSURLRequest(URL: url)
}
}
Swish Request.parse
struct CommentRequest: Request {
typealias ResponseObject = Comment
let id: Int
func build() -> NSURLRequest {
let url = NSURL(string: "https://www.example.com/comments/(id)")!
return NSURLRequest(URL: url)
}
func parse(j: JSON) -> Result<Comment, SwishError> {
return .fromDecoded(Comment.decode(j)) // Default
return .fromDecoded(j <| "comment") // Root key
}
}
Testing
Testing Retrieving a Comment
itBehavesLike(.GETRequest, request: CommentRequest(id: 1))
it("points to /comments/:id") {
let request = CommentRequest(id: 1)
expect(request.build()).to(hitEndpoint("/comments/1"))
}
Testing Creating a Comment
itBehavesLike(.POSTRequest, request: CreateCommentRequest(text: "", user: ""))
it("points to /comments") {
let request = CreateCommentRequest(text: "", user: "")
expect(request.build()).to(hitEndpoint("/comments"))
}
it("has a payload with the text and user") {
let request = CreateCommentRequest(text: "Hi!", user: "ralph")
expect(request.build()).to(havePayload([
"text": "Hi!",
"user": "ralph"
]))
}
Stubbing the Network
it("completes the full request cycle") {
let request = CommentRequest(id: 1)
stub(request).with(.comment)
var response: Comment? = .None
APIClient().performRequest(request) { response = $0.value }
expect(response)
.toEventually(equal(Comment(id: 1, text: "Hallo", user: "ralph")))
}
What else can you do
with Swish?
What else can you do with Swish?
1. Dependency injection of APIClient, protocol Client, for
testing
2. Cancel in-flight requests
3. Execute requests on different queues.
4. Support arbitrary JSON parsers or response types.
5. Anything you want.
Thanks y'all. Questions?
• https://tbot.io/swish-talk
• @jakecraige

More Related Content

What's hot

Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDB
Jeff Yemin
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
Maxim Kulsha
 

What's hot (20)

#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
 
Codable routing
Codable routingCodable routing
Codable routing
 
The Ring programming language version 1.7 book - Part 7 of 196
The Ring programming language version 1.7 book - Part 7 of 196The Ring programming language version 1.7 book - Part 7 of 196
The Ring programming language version 1.7 book - Part 7 of 196
 
greenDAO
greenDAOgreenDAO
greenDAO
 
Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDB
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
Selenium cheat sheet
Selenium cheat sheetSelenium cheat sheet
Selenium cheat sheet
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flow
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
 
Testable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScriptTestable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScript
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net Core
 
The Ring programming language version 1.5.2 book - Part 39 of 181
The Ring programming language version 1.5.2 book - Part 39 of 181The Ring programming language version 1.5.2 book - Part 39 of 181
The Ring programming language version 1.5.2 book - Part 39 of 181
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Protocol Oriented JSON Parsing in Swift
Protocol Oriented JSON Parsing in SwiftProtocol Oriented JSON Parsing in Swift
Protocol Oriented JSON Parsing in Swift
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
Drivers APIs and Looking Forward
Drivers APIs and Looking ForwardDrivers APIs and Looking Forward
Drivers APIs and Looking Forward
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.
 

Viewers also liked

Viewers also liked (17)

Aswathy ppt
Aswathy pptAswathy ppt
Aswathy ppt
 
Niyas khan
Niyas khanNiyas khan
Niyas khan
 
magnetism
magnetismmagnetism
magnetism
 
Phrases in english
Phrases in englishPhrases in english
Phrases in english
 
The esperanto generator
The esperanto generatorThe esperanto generator
The esperanto generator
 
Dispersion -copy
Dispersion  -copyDispersion  -copy
Dispersion -copy
 
Refraction
RefractionRefraction
Refraction
 
Cap4
Cap4Cap4
Cap4
 
Building Hybrid Apps with Ember
Building Hybrid Apps with EmberBuilding Hybrid Apps with Ember
Building Hybrid Apps with Ember
 
Researching Buyers and How They Buy
Researching Buyers and How They BuyResearching Buyers and How They Buy
Researching Buyers and How They Buy
 
IMA Group - Analisi del legame Performance Strategia
IMA Group - Analisi del legame Performance StrategiaIMA Group - Analisi del legame Performance Strategia
IMA Group - Analisi del legame Performance Strategia
 
Dailymotion for Xbox
Dailymotion for XboxDailymotion for Xbox
Dailymotion for Xbox
 
EXOR - Corporate Strategy - 2009-2013
EXOR - Corporate Strategy - 2009-2013EXOR - Corporate Strategy - 2009-2013
EXOR - Corporate Strategy - 2009-2013
 
Organization Performance at Accenture
Organization Performance at AccentureOrganization Performance at Accenture
Organization Performance at Accenture
 
Periscope
PeriscopePeriscope
Periscope
 
Apple & Dell - Financial Analysis 2008 - 2011
Apple & Dell - Financial Analysis 2008 - 2011Apple & Dell - Financial Analysis 2008 - 2011
Apple & Dell - Financial Analysis 2008 - 2011
 
Anilkumar Resume
Anilkumar ResumeAnilkumar Resume
Anilkumar Resume
 

Similar to Modern Networking with Swish

CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
titanlambda
 

Similar to Modern Networking with Swish (20)

async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Go react codelab
Go react codelabGo react codelab
Go react codelab
 
dotSwift - From Problem to Solution
dotSwift - From Problem to SolutiondotSwift - From Problem to Solution
dotSwift - From Problem to Solution
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with Swag
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
Socket.io
Socket.ioSocket.io
Socket.io
 
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsNeo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and Operations
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and Operations
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Express.pdf
Express.pdfExpress.pdf
Express.pdf
 
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & OperationsGraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 

Recently uploaded

RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
Atif Razi
 
Digital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfDigital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdf
AbrahamGadissa
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
Kamal Acharya
 

Recently uploaded (20)

ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES  INTRODUCTION UNIT-IENERGY STORAGE DEVICES  INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdf
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
 
Toll tax management system project report..pdf
Toll tax management system project report..pdfToll tax management system project report..pdf
Toll tax management system project report..pdf
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Digital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfDigital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdf
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptx
 

Modern Networking with Swish

  • 2.
  • 5. Setting up a Model with Argo struct Comment { let id: Int let text: String let user: String } extension Comment: Decodable { // Assume: { "id": 1, "commentText": "Hello world", "user": "ralph" } static func decode(json: JSON) -> Decoded<Comment> { return curry(Comment.init) <^> json <| "id" <*> json <| "commentText" <*> json <| "user" } }
  • 6. Building a GET Request struct CommentRequest: Request { typealias ResponseObject = Comment let id: Int func build() -> NSURLRequest { let url = NSURL( string: "https://www.example.com/comments/(id)" )! return NSURLRequest(URL: url) } }
  • 7. Executing the GET Request let request = CommentRequest(id: 1) APIClient().performRequest(request) { result in switch result { // Result<Comment, SwishError> case let .Success(comment): print("Here's the comment: (comment)") case let .Failure(error): print("Oh no, an error: (error)") } } // => Comment(id: 1, text: "Hi", user: "ralph")
  • 8. GETs are easy. How about POSTs?
  • 9. Building a POST Request struct CreateCommentRequest: Request { typealias ResponseObject = Comment let text: String let user: String var jsonPayload: [String: AnyObject] { return ["text": text, "user": user] } func build() -> NSURLRequest { // ... } }
  • 10. Building a POST Request struct CreateCommentRequest: Request { // ... func build() -> NSURLRequest { let url = NSURL(string: "https://www.example.com/comments")! let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.jsonPayload = jsonPayload return request } }
  • 11. Executing the POST Request let request = CreateCommentRequest(text: "Hola", user: "ralph") APIClient().performRequest(request) { result in switch result { // Result<Comment, SwishError> case let .Success(comment): print("Here's the comment: (value)") case let .Failure(error): print("Oh no, an error: (error)") } } // => Comment(id: 2, text: "Hola", user: "ralph")
  • 12. ! "
  • 13. Let's break it down !
  • 14. Argo's Decodable protocol Decodable { associatedtype DecodedType = Self static func decode(_ json: JSON) -> Decoded<DecodedType> }
  • 15. Argo's Decodable protocol Decodable { associatedtype DecodedType = Self static func decode(_ json: JSON) -> Decoded<DecodedType> } extension Comment: Decodable { static func decode(json: JSON) -> Decoded<Comment> { return curry(Comment.init) <^> json <| "id" <*> json <| "commentText" <*> json <| "user" } }
  • 16. Swish's Request protocol Parser { associatedtype Representation static func parse(j: AnyObject) -> Result<Representation, SwishError> } protocol Request { associatedtype ResponseObject associatedtype ResponseParser: Parser = JSON func build() -> NSURLRequest func parse(j: ResponseParser.Representation) -> Result<ResponseObject, SwishError> }
  • 17. Swish's Request protocol Request { associatedtype ResponseObject associatedtype ResponseParser: Parser = JSON func build() -> NSURLRequest func parse(j: ResponseParser.Representation) -> Result<ResponseObject, SwishError> } struct CommentRequest: Request { typealias ResponseObject = Comment let id: Int func build() -> NSURLRequest { let url = NSURL(string: "https://www.example.com/comments/(id)")! return NSURLRequest(URL: url) } }
  • 18. Swish Request.parse struct CommentRequest: Request { typealias ResponseObject = Comment let id: Int func build() -> NSURLRequest { let url = NSURL(string: "https://www.example.com/comments/(id)")! return NSURLRequest(URL: url) } func parse(j: JSON) -> Result<Comment, SwishError> { return .fromDecoded(Comment.decode(j)) // Default return .fromDecoded(j <| "comment") // Root key } }
  • 20. Testing Retrieving a Comment itBehavesLike(.GETRequest, request: CommentRequest(id: 1)) it("points to /comments/:id") { let request = CommentRequest(id: 1) expect(request.build()).to(hitEndpoint("/comments/1")) }
  • 21. Testing Creating a Comment itBehavesLike(.POSTRequest, request: CreateCommentRequest(text: "", user: "")) it("points to /comments") { let request = CreateCommentRequest(text: "", user: "") expect(request.build()).to(hitEndpoint("/comments")) } it("has a payload with the text and user") { let request = CreateCommentRequest(text: "Hi!", user: "ralph") expect(request.build()).to(havePayload([ "text": "Hi!", "user": "ralph" ])) }
  • 22. Stubbing the Network it("completes the full request cycle") { let request = CommentRequest(id: 1) stub(request).with(.comment) var response: Comment? = .None APIClient().performRequest(request) { response = $0.value } expect(response) .toEventually(equal(Comment(id: 1, text: "Hallo", user: "ralph"))) }
  • 23. What else can you do with Swish?
  • 24. What else can you do with Swish? 1. Dependency injection of APIClient, protocol Client, for testing 2. Cancel in-flight requests 3. Execute requests on different queues. 4. Support arbitrary JSON parsers or response types. 5. Anything you want.
  • 25. Thanks y'all. Questions? • https://tbot.io/swish-talk • @jakecraige