Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Two Scoops of Scala
Search
Kārlis Lauva
April 09, 2014
Programming
0
96
Two Scoops of Scala
April tech talk at FullContact
Kārlis Lauva
April 09, 2014
Tweet
Share
More Decks by Kārlis Lauva
See All by Kārlis Lauva
Let's talk about PureScript
karlis
0
68
Going Full Monty with full.monty
karlis
1
83
The Transatlantic Struggle
karlis
0
56
Valsts pārvaldes atvērto datu semantiskās integrācijas procesi
karlis
1
110
Tornado in 1 Hour (or Less)
karlis
4
180
Other Decks in Programming
See All in Programming
Building a Smaller App Binary
kateinoigakukun
2
220
WebComponentsで フレームワークを1ページに共存させる
webuilder240
0
150
TCA魔法学入門🪄
dazy
0
280
Laravel OpenAPIによる"辛くない"スキーマ駆動開発
kentaroutakeda
2
2.1k
デザインシステムで Tailwind CSSとCSS in JSに分散投資をしたら良かった話
fsubal
14
3.4k
Swiftの型推論を学ぼう | Let's Learn About Type Inference in Swift
omochi
2
720
ファイル先頭の use の意味、説明できますか? 〜PHP の namespace と autoloading の関係を正しく理解しよう〜 / namespace and autoloading in php
okashoi
2
470
15分間でふんわり理解するDocker @ Matsuriba MAX
ukwhatn
PRO
1
340
Material 3で Material 2ぽい見た目にする
numeroanddev
2
250
Crafting a Own PHP - ウキウキ手作りミニマリストPHP
uzulla
4
1.1k
Understanding Ast By Looking
inouehi
0
120
Enhancing Applications with Accessibility API
kishikawakatsumi
3
1k
Featured
See All Featured
GraphQLの誤解/rethinking-graphql
sonatard
48
9.1k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
1
3.3k
Unsuck your backbone
ammeep
661
56k
Automating Front-end Workflow
addyosmani
1353
200k
How To Stay Up To Date on Web Technology
chriscoyier
781
250k
Building Effective Engineering Teams - LeadDev
addyosmani
25
1.8k
VelocityConf: Rendering Performance Case Studies
addyosmani
319
23k
Rails Girls Zürich Keynote
gr2m
91
13k
Code Review Best Practice
trishagee
54
15k
Fontdeck: Realign not Redesign
paulrobertlloyd
75
4.8k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
67
38k
The Invisible Customer
myddelton
114
12k
Transcript
Two scoops of Scala & Unfiltered April 2014 FullContact techTalk
@skazhy
Scala? • object oriented and functional programming language • Type
safe • Runs on JVM
Unfiltered? • A toolkit for HTTP in Scala • Really,
really modular • Works with Netty and Jetty • Built for meetup.com realtime API • Makes good use of Scala's idioms
Toolchain • SBT - Scala Build Tool • Best conventions
from Maven world • Iterative development in SBT shell
My setup • IntelliJ + SBT console(s) inside tmux •
IntelliJ 13 has SBT support baked in
Deployment • Works great with Jenkins & Asgard • Minimal
configuration tweaks needed (wait for the next slide)
• A tool for fetching templates for Scala projects •
g8 skazhy/unfiltered-netty-rx • All SBT plugins for deployment and IntelliJ are included Bootstrapping with giter8
Using opinionated RESTful frameworks for microservices?
None
Example time!
object MyPlan extends cycle.Plan with cycle.ThreadPool with ServerErrorResponse { def
intent = { case GET(Path("/")) => ResponseString("Hello!") case OPTIONS(_) => Created ~> Location("/foo") case _ => NotFound } } unfiltered.netty.Http(1337).handler(MyPlan).run()
An Intent is a partial function that pattern matches HTTP
requests
A Plan is a binding between intent and the underlying
interface
Pattern matching • Decomposing data structures to extract certain fields
or validate them • Really powerful in Scala • “routing” mechanism in Unfiltered
None
Match on request methods • Use builtins: GET(_) POST(_) PATCH(_)
• Or define your own: object SPACEJUMP extends Method("SPACEJUMP")
What happens under the hood? class Method(method: String) { def
unapply[T](req: HttpRequest[T]) = if (req.method.equalsIgnoreCase(method)) Some(req) else None } object POST extends Method("POST")
Match on request headers BasicAuth(username, password) UserAgent("Cobook")
...on URN Path("/foobar") Path(Seg("contactLists" :: "v2" :: listId :: Nil))
// Will extract /contactLists/v2/1234
...or query parameters object AccountIdParam extends Params.Extract("numericId", Params.first ~> Params.nonempty
~> Params.long) PATCH(Params(AccountIdParam(accountId))) // Will extract 1234 from PATCH /foo?numericId=1234
None
function composition!
Responses are composable case _ => Unauthorized ~> ResponseString("No pasaran")
~> ResponseHeader("WWW-Authenticate", "Basic realm=foo")
• HTTP requests are stateless • HTTP responses are side
effects
Async made easy case req @ GET(Path("/async")) => val futureOp
= asyncOperation futureOp.onSuccess { case result => req.respond(Ok ~> ResponseString(result)) } futureOp.onFailure { case _ => req.respond(InternalServerError) }
Unfiltered plays well with RxJava too
case req @ GET(Path("/reactive")) => observableOp.subscribe( result => req.respond(ResponseString(result)) _
=> req.respond(InternalServerError) )
What about testing?
• Separate library for testing with Specs2 • Mocking with
Mockito • Comes bundled with the giter8 template unfiltered-specs2
object OperationPostSpec extends Specification { "PATCH /foo" should { lazy
val r = Http(url((host \ "foo").PATCH)) lazy val response = r() "return HTTP 200" in { response.getResponseStatus mustEqual 200 } } }
Consider using Unfiltered when you... • need an async &
lightweight HTTP service • Have separate business logic • Want to leverage the λ-force
Questions?