SlideShare a Scribd company logo
1 of 29
Download to read offline
CALIBAN
FUNCTIONAL GRAPHQL LIBRARY FOR SCALA
Scala Matsuri - October 2020
Scalaの GraphQLライブラリ
WHO AM I?
> Pierre Ricadat aka @ghostdogpr
>
!
exiled to
"
> Developer at devsisters
> Contributor to ZIO
> Creator of Caliban
自己紹介
フランス出身韓
Caliban作者
GRAPHQL ?
GraphQLとは?
GRAPHQL IN A NUTSHELL
> query language for APIs
> server exposes a typed schema
> client requests and receives only what they want
> client and server can use any programming language
> good tooling
GraphQLの
API のためのクエリ言語、スキーマは型付き
GRAPHQL SCHEMA
type Query {
user(id: ID): User
users: [User!]!
}
type User {
id: ID!
name: String!
age: Int
}
GraphQLスキーマ
GRAPHQL QUERY
query {
user(id: "xxx") {
name
age
}
}
GraphQLクエリ
GRAPHQL IN SCALA
> Sangria
> Caliban
> server
> client (including Scala.js support)
ScalaのGraphQLライブラリ
MOTIVATIONS
> minimize boilerplate
> purely functional
> strongly typed
> explicit errors
> user friendly
動機
ボイラープレートの最小化 / 純
DEFINING A SCHEMA
case class User(
id: UUID,
name: String,
age: Option[Int]
)
type User {
id: ID!
name: String!
age: Int
}
スキーマ定義
DEFINING A SCHEMA
case class UserArgs(id: UUID)
case class Query (
user: UserArgs => Option[User]
users: List[User]
)
type Query {
user(id: ID): User
users: [User!]!
}
スキーマ定義
SUPPORTED SCHEMAS
> Int, String, Boolean, List, Option, Tuple...
> Java Time, Java UUID
> Future, ZIO, ZStream
> case classes, sealed traits (derived by Magnolia)
> Monix, Cats Effect, Circe, Refined (via interop)
サポートしているスキーマ
各種基本の型、ライブラリに加え、自分でも
DEFINING A RESOLVER
val query = Query(
args => userService.getUser(args.id),
userService.getAllUsers
)
val api = graphQL(RootResolver(query))
リゾルバーの定義
CHECK YOUR SCHEMA
println(api.render)
/**
type Query {
user(id: ID): User
users: [User!]!
}
type User {
id: ID!
name: String!
age: Int
}
**/
スキーマを表示確認
TEST YOUR API
val query = "query { user(id: "xxx") { name age } }"
for {
interpreter <- api.interpreter
result <- interpreter.execute(query)
} yield result
APIをテストする
SERVE YOUR API
> http4s
> Akka HTTP
> Play Framework
> Finch
val route: HttpRoutes[Task] = Http4sAdapter.makeHttpService(interpreter)
APIをサーバーで動かす
N + 1 PROBLEM
query {
order(id: 12345) {
name
products {
name
}
}
}
NAIVE
for {
order <- getOrder(id)
products <- ZIO.foreachPar(order.pIds)(getProduct)
} yield Order(order.name, products)
n + 1 requests
そのままだと・・・
N+1回のリクエスト
OPTIMIZED
for {
order <- getOrder(id)
products <- ZQuery.foreachPar(order.pIds)(getProduct)
} yield Order(order.name, products)
2 requests
最適化すると
2回のリクエスト
ZQUERY
case class GetProduct(id: Int) extends Request[Throwable, Product]
val ProductDataSource =
DataSource.fromFunctionBatchedM("ProductDataSource")(
requests => dbService.getProducts(requests.map(_.id))
)
def getProduct(id: Int): ZQuery[Any, Throwable, Product] =
ZQuery.fromRequest(GetProduct(id))(ProductDataSource)
> See zio-query
ZQueryを使うと
WRAPPERS
> parsing
> validation
> execution
> field execution
> whole execution
ラッパー
パース、
BUILTIN WRAPPERS
val api = graphQL(...) @@
maxDepth(30) @@
maxFields(200) @@
timeout(10 seconds) @@
printSlowQueries(1 second)
> Apollo Tracing, Apollo Caching, Apollo Persisted
Queries, etc.
組み
Apolloのトレース、キャシュ、永
MORE FEATURES
> combine APIs
> annotations
> code generation tool
> schema diff
> Apollo Federation
他の機能
APIの結合、アノテーション、コード生成ツール等
CALIBAN CLIENT
> no boilerplate
> no more string copy-pasting
> no need for aliases, fragments, etc
Calibanクライアント
無ボイラープレート、alias や fragment もいらない
STEP 1: CODEGEN TOOL
calibanGenClient <schemaPath> <outputPath>
type Location {
latitude: Float!
longitude: Float!
}
⬇
type Location
object Location {
def latitude: SelectionBuilder[Location, Double] = (...)
def longitude: SelectionBuilder[Location, Double] = (...)
}
コード生成ツール
STEP 2: WRITING QUERIES
val location =
Location.latitude ~ Location.longitude
val query =
Query.search(Some("Berlin Ostbahnhof")) {
Searchable.stations {
Station.name ~ Station.location {
location
}
}
}
クエリを書く
STEP 3: RUNNING QUERIES
val request = query.toRequest(uri)
SttpClient.send(request)
> Response is already parsed into Scala types
> Use the sttp backend of your choice (including Scala.js)
クエリの
レスポンスはScalaの型としてパース /Scala.jsを含み、
好きなsttpバックエンドを使用可能
CURRENT STATE
> Recently celebrated 1st birthday
> Already 520 stars on github
> Built by 45 contributors
#
現在の
開 1年 /520スター/45コントリビューター/パフォーマ
ンス改善
THANKS!
> Website: https://ghostdogpr.github.io/caliban/
> Resources, FAQ, Examples
> ZIO Discord: #caliban
> Twitter: @ghostdogpr
ご
QUESTIONS?
質問はありますか?

More Related Content

What's hot

Présentation spring data Matthieu Briend
Présentation spring data  Matthieu BriendPrésentation spring data  Matthieu Briend
Présentation spring data Matthieu Briend
SOAT
 

What's hot (20)

Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Angular state Management-NgRx
Angular state Management-NgRxAngular state Management-NgRx
Angular state Management-NgRx
 
React&redux
React&reduxReact&redux
React&redux
 
RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
React hooks
React hooksReact hooks
React hooks
 
What is OOP?
What is OOP?What is OOP?
What is OOP?
 
Izumi 1.0: Your Next Scala Stack
Izumi 1.0: Your Next Scala StackIzumi 1.0: Your Next Scala Stack
Izumi 1.0: Your Next Scala Stack
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Oop java
Oop javaOop java
Oop java
 
Jetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIJetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UI
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Decorator Design Pattern
Decorator Design PatternDecorator Design Pattern
Decorator Design Pattern
 
No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...
No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...
No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
 
Angular
AngularAngular
Angular
 
Présentation spring data Matthieu Briend
Présentation spring data  Matthieu BriendPrésentation spring data  Matthieu Briend
Présentation spring data Matthieu Briend
 
GMock framework
GMock frameworkGMock framework
GMock framework
 

Similar to Caliban: Functional GraphQL Library for Scala

サーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよサーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよ
koji lin
 
Streaming API で実現する クラウド ⇔ イントラ連携
Streaming API で実現する クラウド ⇔ イントラ連携Streaming API で実現する クラウド ⇔ イントラ連携
Streaming API で実現する クラウド ⇔ イントラ連携
Shinichi Tomita
 
Data api workshop at Co-Edo
Data api workshop at Co-EdoData api workshop at Co-Edo
Data api workshop at Co-Edo
Yuji Takayama
 

Similar to Caliban: Functional GraphQL Library for Scala (20)

API Gateway / AWS CLI
API Gateway / AWS CLIAPI Gateway / AWS CLI
API Gateway / AWS CLI
 
GraphQL with scala
GraphQL with scalaGraphQL with scala
GraphQL with scala
 
Scala on Hadoop
Scala on HadoopScala on Hadoop
Scala on Hadoop
 
ソーシャルアプリ勉強会(第一回資料)配布用
ソーシャルアプリ勉強会(第一回資料)配布用ソーシャルアプリ勉強会(第一回資料)配布用
ソーシャルアプリ勉強会(第一回資料)配布用
 
Tokyo React.js #3 Meetup (ja): Missing Pages: ReactJS/GraphQL/RelayJS
Tokyo React.js #3 Meetup (ja): Missing Pages: ReactJS/GraphQL/RelayJSTokyo React.js #3 Meetup (ja): Missing Pages: ReactJS/GraphQL/RelayJS
Tokyo React.js #3 Meetup (ja): Missing Pages: ReactJS/GraphQL/RelayJS
 
サーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよサーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよ
 
JapanDreamin24_はじめてのGraphQL×LWC.pptx
JapanDreamin24_はじめてのGraphQL×LWC.pptxJapanDreamin24_はじめてのGraphQL×LWC.pptx
JapanDreamin24_はじめてのGraphQL×LWC.pptx
 
DVGA writeup
DVGA writeupDVGA writeup
DVGA writeup
 
AWS Black Belt Tech シリーズ 2015 - Amazon API Gateway
AWS Black Belt Tech シリーズ 2015 - Amazon API GatewayAWS Black Belt Tech シリーズ 2015 - Amazon API Gateway
AWS Black Belt Tech シリーズ 2015 - Amazon API Gateway
 
Streaming API で実現する クラウド ⇔ イントラ連携
Streaming API で実現する クラウド ⇔ イントラ連携Streaming API で実現する クラウド ⇔ イントラ連携
Streaming API で実現する クラウド ⇔ イントラ連携
 
Data api workshop at Co-Edo
Data api workshop at Co-EdoData api workshop at Co-Edo
Data api workshop at Co-Edo
 
初めての Data api cms どうでしょう - 大阪夏の陣
初めての Data api   cms どうでしょう - 大阪夏の陣初めての Data api   cms どうでしょう - 大阪夏の陣
初めての Data api cms どうでしょう - 大阪夏の陣
 
Angular.jsについてちょっとしゃべる
Angular.jsについてちょっとしゃべるAngular.jsについてちょっとしゃべる
Angular.jsについてちょっとしゃべる
 
Salesforce DUG Japan Meetup#9(REST API, Metadata API etc)
Salesforce DUG Japan Meetup#9(REST API, Metadata API etc)Salesforce DUG Japan Meetup#9(REST API, Metadata API etc)
Salesforce DUG Japan Meetup#9(REST API, Metadata API etc)
 
Next2Dで始めるゲーム開発 - Game Development Starting with Next2D
Next2Dで始めるゲーム開発  - Game Development Starting with Next2DNext2Dで始めるゲーム開発  - Game Development Starting with Next2D
Next2Dで始めるゲーム開発 - Game Development Starting with Next2D
 
Azure で Serverless 初心者向けタッチ&トライ
Azure で Serverless 初心者向けタッチ&トライAzure で Serverless 初心者向けタッチ&トライ
Azure で Serverless 初心者向けタッチ&トライ
 
初めての Data api
初めての Data api初めての Data api
初めての Data api
 
GitHub Actions + Cloudflare API
GitHub Actions + Cloudflare APIGitHub Actions + Cloudflare API
GitHub Actions + Cloudflare API
 
DynamoDB Streamを使ったリアルタイム分析
DynamoDB Streamを使ったリアルタイム分析DynamoDB Streamを使ったリアルタイム分析
DynamoDB Streamを使ったリアルタイム分析
 
Alfresco勉強会#36 alfresco 5でカスタムREST APIを作ってみよう
Alfresco勉強会#36 alfresco 5でカスタムREST APIを作ってみようAlfresco勉強会#36 alfresco 5でカスタムREST APIを作ってみよう
Alfresco勉強会#36 alfresco 5でカスタムREST APIを作ってみよう
 

Recently uploaded

Recently uploaded (11)

Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
 
LoRaWANスマート距離検出センサー DS20L カタログ LiDARデバイス
LoRaWANスマート距離検出センサー  DS20L  カタログ  LiDARデバイスLoRaWANスマート距離検出センサー  DS20L  カタログ  LiDARデバイス
LoRaWANスマート距離検出センサー DS20L カタログ LiDARデバイス
 
論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding
論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding
論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding
 
新人研修 後半 2024/04/26の勉強会で発表されたものです。
新人研修 後半        2024/04/26の勉強会で発表されたものです。新人研修 後半        2024/04/26の勉強会で発表されたものです。
新人研修 後半 2024/04/26の勉強会で発表されたものです。
 
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアルLoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
 
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
 
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
 
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
 
論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games
論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games
論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games
 
論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...
論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...
論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...
 
Observabilityは従来型の監視と何が違うのか(キンドリルジャパン社内勉強会:2022年10月27日発表)
Observabilityは従来型の監視と何が違うのか(キンドリルジャパン社内勉強会:2022年10月27日発表)Observabilityは従来型の監視と何が違うのか(キンドリルジャパン社内勉強会:2022年10月27日発表)
Observabilityは従来型の監視と何が違うのか(キンドリルジャパン社内勉強会:2022年10月27日発表)
 

Caliban: Functional GraphQL Library for Scala

  • 1. CALIBAN FUNCTIONAL GRAPHQL LIBRARY FOR SCALA Scala Matsuri - October 2020 Scalaの GraphQLライブラリ
  • 2. WHO AM I? > Pierre Ricadat aka @ghostdogpr > ! exiled to " > Developer at devsisters > Contributor to ZIO > Creator of Caliban 自己紹介 フランス出身韓 Caliban作者
  • 4. GRAPHQL IN A NUTSHELL > query language for APIs > server exposes a typed schema > client requests and receives only what they want > client and server can use any programming language > good tooling GraphQLの API のためのクエリ言語、スキーマは型付き
  • 5. GRAPHQL SCHEMA type Query { user(id: ID): User users: [User!]! } type User { id: ID! name: String! age: Int } GraphQLスキーマ
  • 6. GRAPHQL QUERY query { user(id: "xxx") { name age } } GraphQLクエリ
  • 7. GRAPHQL IN SCALA > Sangria > Caliban > server > client (including Scala.js support) ScalaのGraphQLライブラリ
  • 8. MOTIVATIONS > minimize boilerplate > purely functional > strongly typed > explicit errors > user friendly 動機 ボイラープレートの最小化 / 純
  • 9. DEFINING A SCHEMA case class User( id: UUID, name: String, age: Option[Int] ) type User { id: ID! name: String! age: Int } スキーマ定義
  • 10. DEFINING A SCHEMA case class UserArgs(id: UUID) case class Query ( user: UserArgs => Option[User] users: List[User] ) type Query { user(id: ID): User users: [User!]! } スキーマ定義
  • 11. SUPPORTED SCHEMAS > Int, String, Boolean, List, Option, Tuple... > Java Time, Java UUID > Future, ZIO, ZStream > case classes, sealed traits (derived by Magnolia) > Monix, Cats Effect, Circe, Refined (via interop) サポートしているスキーマ 各種基本の型、ライブラリに加え、自分でも
  • 12. DEFINING A RESOLVER val query = Query( args => userService.getUser(args.id), userService.getAllUsers ) val api = graphQL(RootResolver(query)) リゾルバーの定義
  • 13. CHECK YOUR SCHEMA println(api.render) /** type Query { user(id: ID): User users: [User!]! } type User { id: ID! name: String! age: Int } **/ スキーマを表示確認
  • 14. TEST YOUR API val query = "query { user(id: "xxx") { name age } }" for { interpreter <- api.interpreter result <- interpreter.execute(query) } yield result APIをテストする
  • 15. SERVE YOUR API > http4s > Akka HTTP > Play Framework > Finch val route: HttpRoutes[Task] = Http4sAdapter.makeHttpService(interpreter) APIをサーバーで動かす
  • 16. N + 1 PROBLEM query { order(id: 12345) { name products { name } } }
  • 17. NAIVE for { order <- getOrder(id) products <- ZIO.foreachPar(order.pIds)(getProduct) } yield Order(order.name, products) n + 1 requests そのままだと・・・ N+1回のリクエスト
  • 18. OPTIMIZED for { order <- getOrder(id) products <- ZQuery.foreachPar(order.pIds)(getProduct) } yield Order(order.name, products) 2 requests 最適化すると 2回のリクエスト
  • 19. ZQUERY case class GetProduct(id: Int) extends Request[Throwable, Product] val ProductDataSource = DataSource.fromFunctionBatchedM("ProductDataSource")( requests => dbService.getProducts(requests.map(_.id)) ) def getProduct(id: Int): ZQuery[Any, Throwable, Product] = ZQuery.fromRequest(GetProduct(id))(ProductDataSource) > See zio-query ZQueryを使うと
  • 20. WRAPPERS > parsing > validation > execution > field execution > whole execution ラッパー パース、
  • 21. BUILTIN WRAPPERS val api = graphQL(...) @@ maxDepth(30) @@ maxFields(200) @@ timeout(10 seconds) @@ printSlowQueries(1 second) > Apollo Tracing, Apollo Caching, Apollo Persisted Queries, etc. 組み Apolloのトレース、キャシュ、永
  • 22. MORE FEATURES > combine APIs > annotations > code generation tool > schema diff > Apollo Federation 他の機能 APIの結合、アノテーション、コード生成ツール等
  • 23. CALIBAN CLIENT > no boilerplate > no more string copy-pasting > no need for aliases, fragments, etc Calibanクライアント 無ボイラープレート、alias や fragment もいらない
  • 24. STEP 1: CODEGEN TOOL calibanGenClient <schemaPath> <outputPath> type Location { latitude: Float! longitude: Float! } ⬇ type Location object Location { def latitude: SelectionBuilder[Location, Double] = (...) def longitude: SelectionBuilder[Location, Double] = (...) } コード生成ツール
  • 25. STEP 2: WRITING QUERIES val location = Location.latitude ~ Location.longitude val query = Query.search(Some("Berlin Ostbahnhof")) { Searchable.stations { Station.name ~ Station.location { location } } } クエリを書く
  • 26. STEP 3: RUNNING QUERIES val request = query.toRequest(uri) SttpClient.send(request) > Response is already parsed into Scala types > Use the sttp backend of your choice (including Scala.js) クエリの レスポンスはScalaの型としてパース /Scala.jsを含み、 好きなsttpバックエンドを使用可能
  • 27. CURRENT STATE > Recently celebrated 1st birthday > Already 520 stars on github > Built by 45 contributors # 現在の 開 1年 /520スター/45コントリビューター/パフォーマ ンス改善
  • 28. THANKS! > Website: https://ghostdogpr.github.io/caliban/ > Resources, FAQ, Examples > ZIO Discord: #caliban > Twitter: @ghostdogpr ご