SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
GRAPHQL
ABOUT ME
Bernd Alter
CTO of VOTUM GmbH
bernd.alter@votum.de
@bazoo0815
AGENDA
Basic introduction to GraphQL
Schema definition
Queries & Mutations
GraphiQL - the GraphQL GUI
Keyset pagination
Experiences, tips & tricks
DEFINITION
GraphQL vs Relay vs React
React = open-source JS library for building user interfaces
Relay = client-side application framework based on React
GraphQL = server-side query language implementation
GraphQL server Data sourcesVarious client apps
JSON
payload
GraphQL
queries
WHAT IS GRAPHQL?
query language
created by Facebook 2012
open-source'd in 2015
KEY FEATURES
strongly typed objects and fields
highly customizable queries
nested/parallel objects in a single request
no versioning necessary
data aggregation from multiple sources
integrated GUI with auto-completion & error check
GRAPHQL IN SYMFONY
several bundles available
overblog/GraphQLBundle
suribit/GraphQLBundle
Youshido/GraphQLBundle
... (see links)
composer require overblog/GraphQLBundle
# also installs base bundle `webonyx/graphql-php`
GRAPHQL SCHEMA
Type (for fields/attributes)
Builder
Connection
Edges
Node
Cursor
Union
Interface
Resolver
SIMPLE TYPES
Type Example(s)
Int 1 25 432
Float 1.23 7.6
String "Any string"
Boolean true false
Enum 0 (=unknown)
1 (=male)
2 (=female)
SIMPLE TYPES (EXAMPLE)
Article:
type: object
fields:
id:
type: Int! <- Exclamation mark = required/not- null
headline:
type: String!
description: "A description can be added anywhere"
featured:
type: Boolean
SPECIAL TYPE: ID
global identifier
base64-encoded string
unique application-wide(!)
Article:
type: object
fields:
id:
type: ID! (instead of Int!)
Example:
"YXJ0aWNsZToxMjY=" -> "article:126"
BUILDER
reusable and configurable 'templates' or 'functions'
field builder (builder)
argument builder (argsBuilder)
FIELD BUILDER (EXAMPLE)
#app/config/config.yml
overblog_graphql:
#...
definitions:
#...
builders:
field:
- alias: "RawId"
class: "MyBundleGraphQLFieldRawIdField"
<?php
class RawIdField implements MappingInterface
{
public function toMappingDefinition(array $config)
{
$name = $config[ 'name'] ?? 'id';
$type = $config[ 'type'] ?? 'Int!';
return [
'description' => 'The raw ID of an object' ,
'type' => $type,
'resolve' => '@=value.' . name,
];
}
}
# in schema definition
Article:
type: object
fields:
rawId:
builder: RawId
...
Video:
type: object
fields:
rawId:
builder: RawId
builderConfig:
name: idVideo
type: String
...
NESTING OF OBJECTS
Article:
type: object
fields:
id:
type: ID!
...
artists:
type: "[Artist]"
images:
type: "[Image]"
Artist:
type: object
fields:
id:
type: ID!
name:
type: String!
Image:
type: object
fields:
id:
type: ID!
url:
type: String!
CONNECTIONS
lists of objects
used for cursor-based (or keyset) pagination
can have arguments
(for filtering, sorting, aggregation)
connection: {
edges: [
{
node: {
id
...
}
}
],
pageInfo: {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
CONNECTIONS (EXAMPLE)
ArticleConnection :
type: relay-connection
config:
nodeType: Article
allArticles:
type: ArticleConnection
argsBuilder: ConnectionArgs
args:
artist:
type: Int
description: "Artist id, e.g. 525338 for artist 'Rihanna'"
dateFrom:
type: String
description: "Filter connection by date (greater than or equal)"
dateTo:
type: String
description: "Filter connection by date (lower than or equal)"
resolve: "@=resolver('article_connection', [args])"
UNIONS
Use it to ...
... handle multiple object types in one field
... deal with heterogeneous structures
UNIONS: EXAMPLE
Schema/Query
Content:
type: union
config:
types: [Article,Product]
Article:
type: object
fields:
headline:
type: String!
Product:
type: object
fields:
title:
type: String!
query Root {
content(artist: "Rihanna") {
... on Article {
__typename
id
headline
}
... on Product {
__typename
id
title
}
}
}
UNIONS: EXAMPLE
Response
{
"data": {
"content": [
{
"__typename": "Product",
"id": "QXJ0aWNsZToyMzc4OTI=" ,
"title": "Unapologetic"
},
{
"__typename": "Article",
"id": "QXJ0aWNsZToyMzgyMjg=" ,
"headline": "ECHO 2017: Rihanna ist fÃŒr den deutschen Musikpreis nominiert"
},
{
"__typename": "Product",
"id": "QXJ0aWNsZToyMzgyMjU=" ,
"title": "ANTI"
},
{
"__typename": "Product",
"id": "QXJ0aWNsZToyMzgyMjY=" ,
"title": "Diamonds"
}
]
}
}
INTERFACES
just like in PHP
objects can have multiple interfaces
not cascading
object can implement interfaces
interface cannot implement interfaces
SeoContent:
type: interface
config:
fields:
seoKeywords:
type: String
Article:
type: object
config:
interfaces: [SeoContent, Node]
fields:
id:
type: ID!
headline:
type: String!
seoKeywords:
type: String
# NOT POSSIBLE
OtherInterface:
type: interface
config:
interfaces: [SeoContent]
RESOLVER
connecting objects/fields to methods
# schema definition in Query.types.yml
Query:
type: object
config:
fields:
articles:
type: ArticleConnection
args:
type:
type: ArticleType
artist:
type: Int
resolve: "@=resolver('article_connection', [args])"
RESOLVER
# config in services.yml
services:
my.graphql.resolver.content:
class: MyGraphQlBundle ResolverContentResolver
tags:
- { name: overblog_graphql.resolver, alias: "root_query", method: "resolveRootQuery" }
- { name: overblog_graphql.resolver, alias: "article", method: "resolveArticle" }
- { name: overblog_graphql.resolver, alias: "article_connection" , method: "resolveArticleConnection" }
# in class MyGraphQlBundleResolverContentResolver
<?php
...
/**
* @param Argument $argument
* @return ArticleConnectionObject
*/
public function resolveArticleConnection (Argument $argument)
{
if (isset($argument['artist']) {
$filters[] = $this->createArtistFilter($argument);
}
/** other code ... */
return $this->getArticleConnection($filters);
}
REQUESTS
Queries
Mutations
Fragments
Variables
QUERY
read-only request
highly customizable
nesting of objects
any combination of fields
multiple resources in one request
query Root {
article(id: 123) {
id
headline
}
videos(first: 5) {
title
url
}
artist(name: "Rihanna") {
name
articles( first: 2, sortBy: "date")
headline
}
}
}
MUTATION
data changing request
requires payload object
# Request
mutation myLogin($input: CredentialsInput!) {
loginUser(input: $input) {
userName
loginSuccessful
}
}
# Payload (variables)
{
"input": {
"email": "me@email.com" ,
"password": "123456",
}
}
# Response
{
"data": {
"loginEmailUser" : {
"userName": "Max",
"loginSuccessful" : true
}
}
}
FRAGMENTS
reusable request pieces
nesting allowed
beware of (infinite) loops!
query Root {
article(id: 123) {
...articleFragment
}
artist(name: "Rihanna") {
name
articles( first: 2, sortBy: "date")
...articleFragment
}
}
}
fragment articleFragment on Article {
id
headline
}
fragment artistFragment on Artist {
name
articles {
...articleFragment
}
}
fragment articleFragment on Article {
id
headline
artist {
...artistFragment
}
}
VARIABLES
needed for payload objects (see mutations)
reusable values/parameters
GRAPHIQL
built-in GUI
available in dev-
mode under
auto-generated docs
sidebar
good demo:
/graphiql
swapi-
graphql
GRAPHIQL
DEMO!
KEYSET PAGINATION
WHAT IS IT ABOUT?
usually offset is used
overhead of read-ahead
using cursor containing
required information
only read what you need
# OFFSET
SELECT * FROM articles
ORDER BY date DESC, id DESC
LIMIT 10 OFFSET 50;
# KEYSET
# cursor: date=2017-03-29, id=165
SELECT * FROM articles
WHERE date < :cursor_date
OR (date = :cursor_date AND id < :cursor_id)
ORDER BY date DESC, id DESC
LIMIT 10;
KEYSET PAGINATION
OFFSET VS KEYSET
Source: http://blog.novatec-gmbh.de/art-pagination-offset-vs-value-based-paging/
KEYSET PAGINATION
Advantages Disadvantages
'real' pagination no page browsing
(only previous and next)
better performance hard(er) to implement
good for endless scrolling
PROBLEMS / PITFALLS
resolvers are atomic
agnostic to parent/child objects
(potential) need to forward settings
loss of control about queries
can lead to performance problems
danger of cyclic/recursive queries
NOTES, TIPS & TRICKS
possible to wrap (existing) REST API in GraphQL
prepare application to deal with pre-flight request
(CORS, HTTP method OPTIONS)
add caching (on object level)
filenames for type definitions have to end with .types.yml
use aliases for usage of same object/field in query
query Root {
article(artist: "Rihanna") {
id
headline
}
otherArticle: article(artist: "Kasabian") {
id
headline
}
}
LINKS: DOCUMENTATION
Official website:
Dra RFC Specification (10/2016)
GraphQL: A data query language
GraphQL Schema Language Cheat Sheet
Connections explained:
http://graphql.org/
http://facebook.github.io/graphql/
https://code.facebook.com/posts/1691455094417024
https://wehavefaces.net/graphql-shorthand-notation-cheatsheet-
17cd715861b6
https://dev-blog.apollodata.com/explaining-graphql-connections-
c48b7c3d6976
LINKS: SYMFONY & OTHER
IMPLEMENTATIONS
Reference implementation in PHP:
Symfony bundle:
GraphQL with PHP and the Symfony Framework:
List of implementations for various languages:
https://github.com/webonyx/graphql-php
overblog/GraphQLBundle
https://www.symfony.fi/entry/graphql-with-php-and-the-symfony-
framework
https://github.com/chentsulin/awesome-graphql
LINKS: VIDEOS
by Lee Byron
by Steven Luscher
Exploring GraphQL at react-europe 2015
Zero to GraphQL in 30 Minutes
LINKS: KEYSET PAGINATION
Slides: Pagination done the right way (by Markus Winand):
The art of pagination - Offset vs. value based paging:
https://www.slideshare.net/MarkusWinand/p2d2-
pagination-done-the-postgresql-way
http://blog.novatec-gmbh.de/art-pagination-offset-vs-value-
based-paging/
THANKS FOR LISTENING

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQLRodrigo Prates
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentationVibhor Grover
 
DevNetCreate Workshop - build a react app - React crash course
DevNetCreate Workshop - build a react app - React crash courseDevNetCreate Workshop - build a react app - React crash course
DevNetCreate Workshop - build a react app - React crash courseCisco DevNet
 
An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQLvaluebound
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modulesmonikadeshmane
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)Hafiz Ismail
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Introduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SFIntroduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SFAmazon Web Services
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineJason Terpko
 
How to GraphQL
How to GraphQLHow to GraphQL
How to GraphQLTomasz Bak
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The FutureTracy Lee
 

Was ist angesagt? (20)

Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentation
 
DevNetCreate Workshop - build a react app - React crash course
DevNetCreate Workshop - build a react app - React crash courseDevNetCreate Workshop - build a react app - React crash course
DevNetCreate Workshop - build a react app - React crash course
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQL
 
Graphql
GraphqlGraphql
Graphql
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
 
GraphQL Fundamentals
GraphQL FundamentalsGraphQL Fundamentals
GraphQL Fundamentals
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Introduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SFIntroduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SF
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation Pipeline
 
React & GraphQL
React & GraphQLReact & GraphQL
React & GraphQL
 
How to GraphQL
How to GraphQLHow to GraphQL
How to GraphQL
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
 

Ähnlich wie GraphQL in Symfony

Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansCarol McDonald
 
Elixir, GraphQL and Vue.js
Elixir, GraphQL and Vue.jsElixir, GraphQL and Vue.js
Elixir, GraphQL and Vue.jsJeroen Visser
 
Overview of GraphQL & Clients
Overview of GraphQL & ClientsOverview of GraphQL & Clients
Overview of GraphQL & ClientsPokai Chang
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHPAndrew Rota
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchNikolas Burk
 
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)Rob Crowley
 
Doctrine ORM with eZ Platform REST API and GraphQL
Doctrine ORM with eZ Platform REST API and GraphQLDoctrine ORM with eZ Platform REST API and GraphQL
Doctrine ORM with eZ Platform REST API and GraphQLJani Tarvainen
 
GraphQL the holy contract between client and server
GraphQL the holy contract between client and serverGraphQL the holy contract between client and server
GraphQL the holy contract between client and serverPavel Chertorogov
 
GraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessGraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessConnected Data World
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)Woonsan Ko
 
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...Codemotion
 
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...Codemotion
 
Spring first in Magnolia CMS - Spring I/O 2015
Spring first in Magnolia CMS - Spring I/O 2015Spring first in Magnolia CMS - Spring I/O 2015
Spring first in Magnolia CMS - Spring I/O 2015Tobias Mattsson
 
Let's start GraphQL: structure, behavior, and architecture
Let's start GraphQL: structure, behavior, and architectureLet's start GraphQL: structure, behavior, and architecture
Let's start GraphQL: structure, behavior, and architectureAndrii Gakhov
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
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) ExtensionVMware Tanzu
 

Ähnlich wie GraphQL in Symfony (20)

Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with Netbeans
 
GraphQL + relay
GraphQL + relayGraphQL + relay
GraphQL + relay
 
Elixir, GraphQL and Vue.js
Elixir, GraphQL and Vue.jsElixir, GraphQL and Vue.js
Elixir, GraphQL and Vue.js
 
Overview of GraphQL & Clients
Overview of GraphQL & ClientsOverview of GraphQL & Clients
Overview of GraphQL & Clients
 
HyperGraphQL
HyperGraphQLHyperGraphQL
HyperGraphQL
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHP
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from Scratch
 
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
 
Doctrine ORM with eZ Platform REST API and GraphQL
Doctrine ORM with eZ Platform REST API and GraphQLDoctrine ORM with eZ Platform REST API and GraphQL
Doctrine ORM with eZ Platform REST API and GraphQL
 
GraphQL the holy contract between client and server
GraphQL the holy contract between client and serverGraphQL the holy contract between client and server
GraphQL the holy contract between client and server
 
GraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessGraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database access
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)
 
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
 
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
Michelle Garrett - Build the API you want to see in the world (with GraphQL) ...
 
Spring first in Magnolia CMS - Spring I/O 2015
Spring first in Magnolia CMS - Spring I/O 2015Spring first in Magnolia CMS - Spring I/O 2015
Spring first in Magnolia CMS - Spring I/O 2015
 
Let's start GraphQL: structure, behavior, and architecture
Let's start GraphQL: structure, behavior, and architectureLet's start GraphQL: structure, behavior, and architecture
Let's start GraphQL: structure, behavior, and architecture
 
PostGraphQL
PostGraphQLPostGraphQL
PostGraphQL
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
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
 

Kürzlich hochgeladen

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 

Kürzlich hochgeladen (20)

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 

GraphQL in Symfony

  • 2. ABOUT ME Bernd Alter CTO of VOTUM GmbH bernd.alter@votum.de @bazoo0815
  • 3. AGENDA Basic introduction to GraphQL Schema definition Queries & Mutations GraphiQL - the GraphQL GUI Keyset pagination Experiences, tips & tricks
  • 4. DEFINITION GraphQL vs Relay vs React React = open-source JS library for building user interfaces Relay = client-side application framework based on React GraphQL = server-side query language implementation
  • 5. GraphQL server Data sourcesVarious client apps JSON payload GraphQL queries WHAT IS GRAPHQL? query language created by Facebook 2012 open-source'd in 2015
  • 6. KEY FEATURES strongly typed objects and fields highly customizable queries nested/parallel objects in a single request no versioning necessary data aggregation from multiple sources integrated GUI with auto-completion & error check
  • 7. GRAPHQL IN SYMFONY several bundles available overblog/GraphQLBundle suribit/GraphQLBundle Youshido/GraphQLBundle ... (see links) composer require overblog/GraphQLBundle # also installs base bundle `webonyx/graphql-php`
  • 8. GRAPHQL SCHEMA Type (for fields/attributes) Builder Connection Edges Node Cursor Union Interface Resolver
  • 9. SIMPLE TYPES Type Example(s) Int 1 25 432 Float 1.23 7.6 String "Any string" Boolean true false Enum 0 (=unknown) 1 (=male) 2 (=female)
  • 10. SIMPLE TYPES (EXAMPLE) Article: type: object fields: id: type: Int! <- Exclamation mark = required/not- null headline: type: String! description: "A description can be added anywhere" featured: type: Boolean
  • 11. SPECIAL TYPE: ID global identifier base64-encoded string unique application-wide(!) Article: type: object fields: id: type: ID! (instead of Int!) Example: "YXJ0aWNsZToxMjY=" -> "article:126"
  • 12. BUILDER reusable and configurable 'templates' or 'functions' field builder (builder) argument builder (argsBuilder)
  • 13. FIELD BUILDER (EXAMPLE) #app/config/config.yml overblog_graphql: #... definitions: #... builders: field: - alias: "RawId" class: "MyBundleGraphQLFieldRawIdField" <?php class RawIdField implements MappingInterface { public function toMappingDefinition(array $config) { $name = $config[ 'name'] ?? 'id'; $type = $config[ 'type'] ?? 'Int!'; return [ 'description' => 'The raw ID of an object' , 'type' => $type, 'resolve' => '@=value.' . name, ]; } } # in schema definition Article: type: object fields: rawId: builder: RawId ... Video: type: object fields: rawId: builder: RawId builderConfig: name: idVideo type: String ...
  • 14. NESTING OF OBJECTS Article: type: object fields: id: type: ID! ... artists: type: "[Artist]" images: type: "[Image]" Artist: type: object fields: id: type: ID! name: type: String! Image: type: object fields: id: type: ID! url: type: String!
  • 15. CONNECTIONS lists of objects used for cursor-based (or keyset) pagination can have arguments (for filtering, sorting, aggregation) connection: { edges: [ { node: { id ... } } ], pageInfo: { hasNextPage hasPreviousPage startCursor endCursor } }
  • 16. CONNECTIONS (EXAMPLE) ArticleConnection : type: relay-connection config: nodeType: Article allArticles: type: ArticleConnection argsBuilder: ConnectionArgs args: artist: type: Int description: "Artist id, e.g. 525338 for artist 'Rihanna'" dateFrom: type: String description: "Filter connection by date (greater than or equal)" dateTo: type: String description: "Filter connection by date (lower than or equal)" resolve: "@=resolver('article_connection', [args])"
  • 17. UNIONS Use it to ... ... handle multiple object types in one field ... deal with heterogeneous structures
  • 18. UNIONS: EXAMPLE Schema/Query Content: type: union config: types: [Article,Product] Article: type: object fields: headline: type: String! Product: type: object fields: title: type: String! query Root { content(artist: "Rihanna") { ... on Article { __typename id headline } ... on Product { __typename id title } } }
  • 19. UNIONS: EXAMPLE Response { "data": { "content": [ { "__typename": "Product", "id": "QXJ0aWNsZToyMzc4OTI=" , "title": "Unapologetic" }, { "__typename": "Article", "id": "QXJ0aWNsZToyMzgyMjg=" , "headline": "ECHO 2017: Rihanna ist fÃŒr den deutschen Musikpreis nominiert" }, { "__typename": "Product", "id": "QXJ0aWNsZToyMzgyMjU=" , "title": "ANTI" }, { "__typename": "Product", "id": "QXJ0aWNsZToyMzgyMjY=" , "title": "Diamonds" } ] } }
  • 20. INTERFACES just like in PHP objects can have multiple interfaces not cascading object can implement interfaces interface cannot implement interfaces SeoContent: type: interface config: fields: seoKeywords: type: String Article: type: object config: interfaces: [SeoContent, Node] fields: id: type: ID! headline: type: String! seoKeywords: type: String # NOT POSSIBLE OtherInterface: type: interface config: interfaces: [SeoContent]
  • 21. RESOLVER connecting objects/fields to methods # schema definition in Query.types.yml Query: type: object config: fields: articles: type: ArticleConnection args: type: type: ArticleType artist: type: Int resolve: "@=resolver('article_connection', [args])"
  • 22. RESOLVER # config in services.yml services: my.graphql.resolver.content: class: MyGraphQlBundle ResolverContentResolver tags: - { name: overblog_graphql.resolver, alias: "root_query", method: "resolveRootQuery" } - { name: overblog_graphql.resolver, alias: "article", method: "resolveArticle" } - { name: overblog_graphql.resolver, alias: "article_connection" , method: "resolveArticleConnection" } # in class MyGraphQlBundleResolverContentResolver <?php ... /** * @param Argument $argument * @return ArticleConnectionObject */ public function resolveArticleConnection (Argument $argument) { if (isset($argument['artist']) { $filters[] = $this->createArtistFilter($argument); } /** other code ... */ return $this->getArticleConnection($filters); }
  • 24. QUERY read-only request highly customizable nesting of objects any combination of fields multiple resources in one request query Root { article(id: 123) { id headline } videos(first: 5) { title url } artist(name: "Rihanna") { name articles( first: 2, sortBy: "date") headline } } }
  • 25. MUTATION data changing request requires payload object # Request mutation myLogin($input: CredentialsInput!) { loginUser(input: $input) { userName loginSuccessful } } # Payload (variables) { "input": { "email": "me@email.com" , "password": "123456", } } # Response { "data": { "loginEmailUser" : { "userName": "Max", "loginSuccessful" : true } } }
  • 26. FRAGMENTS reusable request pieces nesting allowed beware of (infinite) loops! query Root { article(id: 123) { ...articleFragment } artist(name: "Rihanna") { name articles( first: 2, sortBy: "date") ...articleFragment } } } fragment articleFragment on Article { id headline } fragment artistFragment on Artist { name articles { ...articleFragment } } fragment articleFragment on Article { id headline artist { ...artistFragment } }
  • 27. VARIABLES needed for payload objects (see mutations) reusable values/parameters
  • 28. GRAPHIQL built-in GUI available in dev- mode under auto-generated docs sidebar good demo: /graphiql swapi- graphql
  • 30. KEYSET PAGINATION WHAT IS IT ABOUT? usually offset is used overhead of read-ahead using cursor containing required information only read what you need # OFFSET SELECT * FROM articles ORDER BY date DESC, id DESC LIMIT 10 OFFSET 50; # KEYSET # cursor: date=2017-03-29, id=165 SELECT * FROM articles WHERE date < :cursor_date OR (date = :cursor_date AND id < :cursor_id) ORDER BY date DESC, id DESC LIMIT 10;
  • 31. KEYSET PAGINATION OFFSET VS KEYSET Source: http://blog.novatec-gmbh.de/art-pagination-offset-vs-value-based-paging/
  • 32. KEYSET PAGINATION Advantages Disadvantages 'real' pagination no page browsing (only previous and next) better performance hard(er) to implement good for endless scrolling
  • 33. PROBLEMS / PITFALLS resolvers are atomic agnostic to parent/child objects (potential) need to forward settings loss of control about queries can lead to performance problems danger of cyclic/recursive queries
  • 34. NOTES, TIPS & TRICKS possible to wrap (existing) REST API in GraphQL prepare application to deal with pre-flight request (CORS, HTTP method OPTIONS) add caching (on object level) filenames for type definitions have to end with .types.yml use aliases for usage of same object/field in query query Root { article(artist: "Rihanna") { id headline } otherArticle: article(artist: "Kasabian") { id headline } }
  • 35. LINKS: DOCUMENTATION Official website: Dra RFC Specification (10/2016) GraphQL: A data query language GraphQL Schema Language Cheat Sheet Connections explained: http://graphql.org/ http://facebook.github.io/graphql/ https://code.facebook.com/posts/1691455094417024 https://wehavefaces.net/graphql-shorthand-notation-cheatsheet- 17cd715861b6 https://dev-blog.apollodata.com/explaining-graphql-connections- c48b7c3d6976
  • 36. LINKS: SYMFONY & OTHER IMPLEMENTATIONS Reference implementation in PHP: Symfony bundle: GraphQL with PHP and the Symfony Framework: List of implementations for various languages: https://github.com/webonyx/graphql-php overblog/GraphQLBundle https://www.symfony.fi/entry/graphql-with-php-and-the-symfony- framework https://github.com/chentsulin/awesome-graphql
  • 37. LINKS: VIDEOS by Lee Byron by Steven Luscher Exploring GraphQL at react-europe 2015 Zero to GraphQL in 30 Minutes
  • 38. LINKS: KEYSET PAGINATION Slides: Pagination done the right way (by Markus Winand): The art of pagination - Offset vs. value based paging: https://www.slideshare.net/MarkusWinand/p2d2- pagination-done-the-postgresql-way http://blog.novatec-gmbh.de/art-pagination-offset-vs-value- based-paging/