SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
1
Augmenting
a legacy {REST} API
with GraphQL
● Started in 2015
● Back end with Ruby on Rails, two mobiles app (Android
and iOS), website
● Good tests coverage but not perfect
● Some functional documentation for critical features
(like payment)
● Small evolutions and dependencies upgrade during the
years
● End of 2019 new big feature: Beehive for Business
Fast and independent
Coworking with self check-in
2
Why did we add
GraphQL ?
1
Specification Development Code is deployed
reviewed
Front-end validates Development
reviewed
New field
is deployed
Front-end needs
a new field
5
Performance
can be an issue
Some fields are
not required
Many endpoints &
representations
of a resource
Some fields are
expensive to
compute
Documentation
By adding tests and using
json-schemas we can make sure
our documentation is up to date
��♂
Data fetching
��♂
Better
performance
��
No graphQL expert
inside our team
Big investmentLearning curve
��
How did we add
GraphQL ?
2
Ask front end if they can use GraphQL API
Start with queries
Added-value is here, we can do mutation later
Write tests if missing
Extract business code from controller into interactor
Write the GraphQL query and types
With an interactor
Extract business code from controller
def index
offers = Offer.all
filtered_offers = offers.available.not_hidden.not_meeting_room
scoped_offers = policy_scope(filtered_offers)
render json: scoped_offers, root: 'offers', serializer: OfferSerializer
end
def index
offers = GetOffers.new.call(current_user: current_user).value!
render json: offers, root: 'offers', serializer: OfferSerializer
end
Query is the entry point
class QueryType < Types::BaseObject
# Add root-level fields here.
# They will be entry points for queries on your schema.
field :offers, [Types::OfferType], null: false
def offers
GetOffers.new.call(
current_user: context[:current_user]
).value!
end
end
Query
FIELDS
offers [Offer!]!
Type is the equivalent of a REST serializer
class OfferType < Types::BaseObject
field :id, ID, null: false
field :name, String, null: false
field :has_access_to_private_offices, Boolean, null: false
field :hidden, Boolean, null: false
field :highlighted, Boolean, null: false
field :ht_price, String, null: false
field :kind, OfferKind, null: false
field :marketing_name, String, null: true
field :multiplier_for_durations, [GraphQL::Types::JSON], null: false
def multiplier_for_durations
object.possible_multipliers.map do |i|
{
string: I18n.t("offers.period.#{object.period}", count: i),
multiplier: i
}
end
end
end
Offer
FIELDS
hasAccessToPrivateOffices Boolean!
hidden Boolean!
highlighted Boolean!
htPrice String!
id ID!
kind OfferKind!
marketingName String!
multiplierForDurations [JSON!]!
name String!
Ask front end if they can use GraphQL API
Start with queries
Added-value is here, we can do mutation later
Write tests if missing
Extract business code from controller into interactor
Write the GraphQL query and types
Adapt your existing tools
Postman => Altair
Is this over ?
3
15
In the REST world it is solved by adding .preload(:offers)
Enterprise.preload(:offers).all
An innocent query…
# SELECT * FROM enterprises (+ 1 query)
Enterprise.all.each do |enterprise|
# SELECT * FROM offers WHERE enterprise_id = ? (n queries)
enterprise.offers.map(&:id)
end
query {
enterprises {
id
offers {
id
}
}
}
...will result in n + 1 queries being made
Result in bad performance
● Batchloading is a generic lazy batching mechanism
● Idea: Delay evaluation to load data in once
https://github.com/exAspArk/batch-loader & https://github.com/graphql/dataloader
class EnterpriseType < Types::BaseObject
field :offers, [Types::OfferType], null: false
def offers
BatchLoader::GraphQL.for(object).batch do |enterprises, loader|
preloader = ActiveRecord::Associations::Preloader.new
preloader.preload(enterprises, :offers)
enterprises.each do |enterprise|
loader.call(enterprise, enterprise.offers)
end
end
end
end
With a custom helper
GraphQL
class EnterpriseType < Types::BaseObject
preload_field :offers, [Types::OfferType], null: false, associations: :offers
end
{REST}
Enterprise.preload(:offers).all
Front end
point of view
4
React
It’s awesome.
Loading state, pagination, caching,
optimistic UI out of the box.
Mobile apps
Neutral
��♂ ��
Mutations
5
Write missing tests
Extract controller code in independant Interactor
Add mutations
createEnterprise
ARGUMENTS
enterpriseRequest CreateEnterpriseRequest!
SUBTYPES
Failure
SuccessOfEnterprise
TYPE
class CreateEnterpriseMutation < Mutations::BaseMutation
argument :enterprise_request, CreateEnterpriseRequestType,
required: true
type failure_union(EnterpriseType)
def resolve(enterprise_request:)
result = CreateEnterprise.new.call(
user: context[:current_user],
params: {
enterprise: enterprise_request.to_h,
}
)
if result.success?
{ success: result.value! }
else
result.failure
end
end
end
FailureOrSuccessOfEnterpriseUnion Union
What’s next ?
6
Handle file upload
Monitoring: everything is under /graphql
Demystify graphQL for the rest of the team
Learning curve
is not that high
Incremental approach
is possible
You can use both
27

Contenu connexe

Tendances

Tendances (20)

apidays LIVE Paris 2021 - Spatially enabling Web APIs through OGC Standards ...
apidays LIVE Paris 2021 - Spatially enabling Web APIs through OGC Standards  ...apidays LIVE Paris 2021 - Spatially enabling Web APIs through OGC Standards  ...
apidays LIVE Paris 2021 - Spatially enabling Web APIs through OGC Standards ...
 
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
 
apidays LIVE Australia 2021 - From apps to APIs: how no-code is transforming ...
apidays LIVE Australia 2021 - From apps to APIs: how no-code is transforming ...apidays LIVE Australia 2021 - From apps to APIs: how no-code is transforming ...
apidays LIVE Australia 2021 - From apps to APIs: how no-code is transforming ...
 
apidays LIVE Paris 2021 - 20 Minutes to Build a Serverless COVID-19 GraphQL A...
apidays LIVE Paris 2021 - 20 Minutes to Build a Serverless COVID-19 GraphQL A...apidays LIVE Paris 2021 - 20 Minutes to Build a Serverless COVID-19 GraphQL A...
apidays LIVE Paris 2021 - 20 Minutes to Build a Serverless COVID-19 GraphQL A...
 
apidays LIVE Jakarta - What will the next generation of API Portals look like...
apidays LIVE Jakarta - What will the next generation of API Portals look like...apidays LIVE Jakarta - What will the next generation of API Portals look like...
apidays LIVE Jakarta - What will the next generation of API Portals look like...
 
apidays LIVE Paris - Data with a mission: a COVID-19 API case study by Matt M...
apidays LIVE Paris - Data with a mission: a COVID-19 API case study by Matt M...apidays LIVE Paris - Data with a mission: a COVID-19 API case study by Matt M...
apidays LIVE Paris - Data with a mission: a COVID-19 API case study by Matt M...
 
apidays LIVE New York 2021 - Service API design validation by Uchit Vyas, KPMG
apidays LIVE New York 2021 - Service API design validation by Uchit Vyas, KPMGapidays LIVE New York 2021 - Service API design validation by Uchit Vyas, KPMG
apidays LIVE New York 2021 - Service API design validation by Uchit Vyas, KPMG
 
Pain Points In API Development? They’re Everywhere
Pain Points In API Development? They’re EverywherePain Points In API Development? They’re Everywhere
Pain Points In API Development? They’re Everywhere
 
apidays LIVE Paris 2021 - What Developers Want by Paul Ardeleanu, Vonage
apidays LIVE Paris 2021 - What Developers Want by Paul Ardeleanu, Vonageapidays LIVE Paris 2021 - What Developers Want by Paul Ardeleanu, Vonage
apidays LIVE Paris 2021 - What Developers Want by Paul Ardeleanu, Vonage
 
Building APIs in a Cloud Native Era
Building APIs in a Cloud Native EraBuilding APIs in a Cloud Native Era
Building APIs in a Cloud Native Era
 
apidays LIVE Australia 2020 - Federating API Development at Australia’s large...
apidays LIVE Australia 2020 - Federating API Development at Australia’s large...apidays LIVE Australia 2020 - Federating API Development at Australia’s large...
apidays LIVE Australia 2020 - Federating API Development at Australia’s large...
 
Executing on API Developer Experience
Executing on API Developer Experience Executing on API Developer Experience
Executing on API Developer Experience
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLEAN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
 
Your API Strategy: Why Boring is Best
Your API Strategy: Why Boring is BestYour API Strategy: Why Boring is Best
Your API Strategy: Why Boring is Best
 
apidays LIVE Australia 2021 - Confessions of a Product Geek : My First API BY...
apidays LIVE Australia 2021 - Confessions of a Product Geek : My First API BY...apidays LIVE Australia 2021 - Confessions of a Product Geek : My First API BY...
apidays LIVE Australia 2021 - Confessions of a Product Geek : My First API BY...
 
APIDays - API Design Workshop
APIDays - API Design WorkshopAPIDays - API Design Workshop
APIDays - API Design Workshop
 
apidays LIVE Paris 2021 - API design is where culture and tech meet each othe...
apidays LIVE Paris 2021 - API design is where culture and tech meet each othe...apidays LIVE Paris 2021 - API design is where culture and tech meet each othe...
apidays LIVE Paris 2021 - API design is where culture and tech meet each othe...
 
apidays LIVE Paris 2021 - Building an Accessible API Spec with Traditional En...
apidays LIVE Paris 2021 - Building an Accessible API Spec with Traditional En...apidays LIVE Paris 2021 - Building an Accessible API Spec with Traditional En...
apidays LIVE Paris 2021 - Building an Accessible API Spec with Traditional En...
 
What do you mean by "API as a Product"?
What do you mean by "API as a Product"?What do you mean by "API as a Product"?
What do you mean by "API as a Product"?
 
apidays LIVE Paris 2021 - Deliver real-time data to customer using Streaming ...
apidays LIVE Paris 2021 - Deliver real-time data to customer using Streaming ...apidays LIVE Paris 2021 - Deliver real-time data to customer using Streaming ...
apidays LIVE Paris 2021 - Deliver real-time data to customer using Streaming ...
 

Similaire à apidays LIVE Paris - Augmenting a Legacy REST API with GraphQL by Clément Villain

C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
Hammad Rajjoub
 

Similaire à apidays LIVE Paris - Augmenting a Legacy REST API with GraphQL by Clément Villain (20)

React and GraphQL at Stripe
React and GraphQL at StripeReact and GraphQL at Stripe
React and GraphQL at Stripe
 
Introduction to Testing GraphQL Presentation
Introduction to Testing GraphQL PresentationIntroduction to Testing GraphQL Presentation
Introduction to Testing GraphQL Presentation
 
Testing Graph QL Presentation (Test Automation)
Testing Graph QL Presentation (Test Automation)Testing Graph QL Presentation (Test Automation)
Testing Graph QL Presentation (Test Automation)
 
apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...
apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...
apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...
 
GraphQL API Crafts presentation
GraphQL API Crafts presentationGraphQL API Crafts presentation
GraphQL API Crafts presentation
 
No Graph Theory Required: Ember and GraphQL in Practice
No Graph Theory Required: Ember and GraphQL in PracticeNo Graph Theory Required: Ember and GraphQL in Practice
No Graph Theory Required: Ember and GraphQL in Practice
 
GraphQL: Enabling a new generation of API developer tools
GraphQL: Enabling a new generation of API developer toolsGraphQL: Enabling a new generation of API developer tools
GraphQL: Enabling a new generation of API developer tools
 
Tutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPTutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHP
 
Implementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCImplementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPC
 
APIdays Paris 2019 - Maintain & Evolve a Public GraphQL API by Aurélien Davi...
APIdays Paris 2019 - Maintain & Evolve a Public  GraphQL API by Aurélien Davi...APIdays Paris 2019 - Maintain & Evolve a Public  GraphQL API by Aurélien Davi...
APIdays Paris 2019 - Maintain & Evolve a Public GraphQL API by Aurélien Davi...
 
What could go wrong with a GraphQL query and can OpenTelemetry help? KubeCon...
What could go wrong  with a GraphQL query and can OpenTelemetry help? KubeCon...What could go wrong  with a GraphQL query and can OpenTelemetry help? KubeCon...
What could go wrong with a GraphQL query and can OpenTelemetry help? KubeCon...
 
Why your APIs should fly first class
Why your APIs should fly first classWhy your APIs should fly first class
Why your APIs should fly first class
 
GraphQL @ Manc.JS (March 2018)
GraphQL @ Manc.JS (March 2018)GraphQL @ Manc.JS (March 2018)
GraphQL @ Manc.JS (March 2018)
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
 
GraphQL over REST at Reactathon 2018
GraphQL over REST at Reactathon 2018GraphQL over REST at Reactathon 2018
GraphQL over REST at Reactathon 2018
 
React Flux to GraphQL
React Flux to GraphQLReact Flux to GraphQL
React Flux to GraphQL
 
GraphQL + relay
GraphQL + relayGraphQL + relay
GraphQL + relay
 
GraphQL APIs is with eZ Platform, a Symfony CMS
GraphQL APIs is with eZ Platform, a Symfony CMSGraphQL APIs is with eZ Platform, a Symfony CMS
GraphQL APIs is with eZ Platform, a Symfony CMS
 

Plus de apidays

Plus de apidays (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - The secrets to Graph success, by Leah Hurwich Adler, ...
Apidays New York 2024 - The secrets to Graph success, by Leah Hurwich Adler, ...Apidays New York 2024 - The secrets to Graph success, by Leah Hurwich Adler, ...
Apidays New York 2024 - The secrets to Graph success, by Leah Hurwich Adler, ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - API Discovery - From Crawl to Run by Rob Dickinson, G...
Apidays New York 2024 - API Discovery - From Crawl to Run by Rob Dickinson, G...Apidays New York 2024 - API Discovery - From Crawl to Run by Rob Dickinson, G...
Apidays New York 2024 - API Discovery - From Crawl to Run by Rob Dickinson, G...
 
Apidays Singapore 2024 - Building with the Planet in Mind by Sandeep Joshi, M...
Apidays Singapore 2024 - Building with the Planet in Mind by Sandeep Joshi, M...Apidays Singapore 2024 - Building with the Planet in Mind by Sandeep Joshi, M...
Apidays Singapore 2024 - Building with the Planet in Mind by Sandeep Joshi, M...
 
Apidays Singapore 2024 - Connecting Cross Border Commerce with Payments by Gu...
Apidays Singapore 2024 - Connecting Cross Border Commerce with Payments by Gu...Apidays Singapore 2024 - Connecting Cross Border Commerce with Payments by Gu...
Apidays Singapore 2024 - Connecting Cross Border Commerce with Payments by Gu...
 
Apidays Singapore 2024 - Privacy Enhancing Technologies for AI by Mark Choo, ...
Apidays Singapore 2024 - Privacy Enhancing Technologies for AI by Mark Choo, ...Apidays Singapore 2024 - Privacy Enhancing Technologies for AI by Mark Choo, ...
Apidays Singapore 2024 - Privacy Enhancing Technologies for AI by Mark Choo, ...
 
Apidays Singapore 2024 - Blending AI and IoT for Smarter Health by Matthew Ch...
Apidays Singapore 2024 - Blending AI and IoT for Smarter Health by Matthew Ch...Apidays Singapore 2024 - Blending AI and IoT for Smarter Health by Matthew Ch...
Apidays Singapore 2024 - Blending AI and IoT for Smarter Health by Matthew Ch...
 
Apidays Singapore 2024 - OpenTelemetry for API Monitoring by Danielle Kayumbi...
Apidays Singapore 2024 - OpenTelemetry for API Monitoring by Danielle Kayumbi...Apidays Singapore 2024 - OpenTelemetry for API Monitoring by Danielle Kayumbi...
Apidays Singapore 2024 - OpenTelemetry for API Monitoring by Danielle Kayumbi...
 
Apidays Singapore 2024 - Connecting Product and Engineering Teams with Testin...
Apidays Singapore 2024 - Connecting Product and Engineering Teams with Testin...Apidays Singapore 2024 - Connecting Product and Engineering Teams with Testin...
Apidays Singapore 2024 - Connecting Product and Engineering Teams with Testin...
 
Apidays Singapore 2024 - The Growing Carbon Footprint of Digitalization and H...
Apidays Singapore 2024 - The Growing Carbon Footprint of Digitalization and H...Apidays Singapore 2024 - The Growing Carbon Footprint of Digitalization and H...
Apidays Singapore 2024 - The Growing Carbon Footprint of Digitalization and H...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays Singapore 2024 - API Monitoring x SRE by Ryan Ashneil and Eugene Wong...
Apidays Singapore 2024 - API Monitoring x SRE by Ryan Ashneil and Eugene Wong...Apidays Singapore 2024 - API Monitoring x SRE by Ryan Ashneil and Eugene Wong...
Apidays Singapore 2024 - API Monitoring x SRE by Ryan Ashneil and Eugene Wong...
 
Apidays Singapore 2024 - A nuanced approach on AI costs and benefits for the ...
Apidays Singapore 2024 - A nuanced approach on AI costs and benefits for the ...Apidays Singapore 2024 - A nuanced approach on AI costs and benefits for the ...
Apidays Singapore 2024 - A nuanced approach on AI costs and benefits for the ...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays Singapore 2024 - How APIs drive business at BNP Paribas by Quy-Doan D...
Apidays Singapore 2024 - How APIs drive business at BNP Paribas by Quy-Doan D...Apidays Singapore 2024 - How APIs drive business at BNP Paribas by Quy-Doan D...
Apidays Singapore 2024 - How APIs drive business at BNP Paribas by Quy-Doan D...
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

apidays LIVE Paris - Augmenting a Legacy REST API with GraphQL by Clément Villain

  • 1. 1 Augmenting a legacy {REST} API with GraphQL
  • 2. ● Started in 2015 ● Back end with Ruby on Rails, two mobiles app (Android and iOS), website ● Good tests coverage but not perfect ● Some functional documentation for critical features (like payment) ● Small evolutions and dependencies upgrade during the years ● End of 2019 new big feature: Beehive for Business Fast and independent Coworking with self check-in 2
  • 3. Why did we add GraphQL ? 1
  • 4. Specification Development Code is deployed reviewed Front-end validates Development reviewed New field is deployed Front-end needs a new field
  • 5. 5 Performance can be an issue Some fields are not required Many endpoints & representations of a resource Some fields are expensive to compute
  • 6. Documentation By adding tests and using json-schemas we can make sure our documentation is up to date ��♂ Data fetching ��♂ Better performance ��
  • 7. No graphQL expert inside our team Big investmentLearning curve ��
  • 8. How did we add GraphQL ? 2
  • 9. Ask front end if they can use GraphQL API Start with queries Added-value is here, we can do mutation later Write tests if missing Extract business code from controller into interactor Write the GraphQL query and types
  • 10. With an interactor Extract business code from controller def index offers = Offer.all filtered_offers = offers.available.not_hidden.not_meeting_room scoped_offers = policy_scope(filtered_offers) render json: scoped_offers, root: 'offers', serializer: OfferSerializer end def index offers = GetOffers.new.call(current_user: current_user).value! render json: offers, root: 'offers', serializer: OfferSerializer end
  • 11. Query is the entry point class QueryType < Types::BaseObject # Add root-level fields here. # They will be entry points for queries on your schema. field :offers, [Types::OfferType], null: false def offers GetOffers.new.call( current_user: context[:current_user] ).value! end end Query FIELDS offers [Offer!]!
  • 12. Type is the equivalent of a REST serializer class OfferType < Types::BaseObject field :id, ID, null: false field :name, String, null: false field :has_access_to_private_offices, Boolean, null: false field :hidden, Boolean, null: false field :highlighted, Boolean, null: false field :ht_price, String, null: false field :kind, OfferKind, null: false field :marketing_name, String, null: true field :multiplier_for_durations, [GraphQL::Types::JSON], null: false def multiplier_for_durations object.possible_multipliers.map do |i| { string: I18n.t("offers.period.#{object.period}", count: i), multiplier: i } end end end Offer FIELDS hasAccessToPrivateOffices Boolean! hidden Boolean! highlighted Boolean! htPrice String! id ID! kind OfferKind! marketingName String! multiplierForDurations [JSON!]! name String!
  • 13. Ask front end if they can use GraphQL API Start with queries Added-value is here, we can do mutation later Write tests if missing Extract business code from controller into interactor Write the GraphQL query and types Adapt your existing tools Postman => Altair
  • 15. 15
  • 16. In the REST world it is solved by adding .preload(:offers) Enterprise.preload(:offers).all An innocent query… # SELECT * FROM enterprises (+ 1 query) Enterprise.all.each do |enterprise| # SELECT * FROM offers WHERE enterprise_id = ? (n queries) enterprise.offers.map(&:id) end query { enterprises { id offers { id } } } ...will result in n + 1 queries being made Result in bad performance
  • 17. ● Batchloading is a generic lazy batching mechanism ● Idea: Delay evaluation to load data in once https://github.com/exAspArk/batch-loader & https://github.com/graphql/dataloader class EnterpriseType < Types::BaseObject field :offers, [Types::OfferType], null: false def offers BatchLoader::GraphQL.for(object).batch do |enterprises, loader| preloader = ActiveRecord::Associations::Preloader.new preloader.preload(enterprises, :offers) enterprises.each do |enterprise| loader.call(enterprise, enterprise.offers) end end end end
  • 18. With a custom helper GraphQL class EnterpriseType < Types::BaseObject preload_field :offers, [Types::OfferType], null: false, associations: :offers end {REST} Enterprise.preload(:offers).all
  • 20. React It’s awesome. Loading state, pagination, caching, optimistic UI out of the box. Mobile apps Neutral ��♂ ��
  • 22. Write missing tests Extract controller code in independant Interactor Add mutations
  • 23. createEnterprise ARGUMENTS enterpriseRequest CreateEnterpriseRequest! SUBTYPES Failure SuccessOfEnterprise TYPE class CreateEnterpriseMutation < Mutations::BaseMutation argument :enterprise_request, CreateEnterpriseRequestType, required: true type failure_union(EnterpriseType) def resolve(enterprise_request:) result = CreateEnterprise.new.call( user: context[:current_user], params: { enterprise: enterprise_request.to_h, } ) if result.success? { success: result.value! } else result.failure end end end FailureOrSuccessOfEnterpriseUnion Union
  • 25. Handle file upload Monitoring: everything is under /graphql Demystify graphQL for the rest of the team
  • 26. Learning curve is not that high Incremental approach is possible You can use both
  • 27. 27