SlideShare une entreprise Scribd logo
1  sur  69
Télécharger pour lire hors ligne
Extend GraphQL
with directives
@neoziro
smooth-code.com
I am Greg Bergé
JavaScript, React & GraphQL trainer
@neoziro
!
github.com/neoziro
"
smooth-code.com#
smooth code
What is a directive?
@include(if: Boolean)
Built-in directives
@include(if: Boolean!)
@skip(if: Boolean!)
@deprecated(reason: String)
@include / @skip
•Query directive
•Can be used on fields and fragments
•Control the scope of query using a
parameter
query Person($includeFilms: Boolean = false) { 

person(personID: 1) { 

name 

height 

mass 

filmConnection(first: 10) @include(if: $includeFilms) { 

edges { 

node { 

title 

} 

} 

} 

} 

}
query Person($skipFilms: Boolean = false) { 

person(personID: 1) { 

name 

height 

mass 

filmConnection(first: 10) @skip(if: $skipFilms) { 

edges { 

node { 

title 

} 

} 

} 

} 

}
@deprecated
•Schema directive
•Can be used on field definitions and
enums
•Marks an element of a GraphQL
schema as no longer supported
type Book { 

name: String 

longName: String @deprecated(reason: "use name instead") 

}
I love it 🤩
I want to create directives!
But why?
•Resolved server-side
→ less computation on client
•Most of GraphQL clients cache queries
→ avoid computation
•Declarative
→ understand code by reading query
query { 

user { 

name @upperCase 

} 

}
Text Formatting
Date Formatting
query { 

user { 

birthDate @dateFormat(format: "DD/MM/YYYY") 

} 

}
Restrictions
type User { 

privateNote: String @requireAuth 

}
Let's do it!
😒
🤔
🤔🤔
🤔🤔🤔
Sorry @leebyron 🤭
Behind a directive
/** 

* Used to conditionally include fields or fragments. 

*/ 

export const GraphQLIncludeDirective = new GraphQLDirective({ 

name: 'include', 

description: 

'Directs the executor to include this field or fragment only when ' + 

'the `if` argument is true.', 

locations: [ 

DirectiveLocation.FIELD, 

DirectiveLocation.FRAGMENT_SPREAD, 

DirectiveLocation.INLINE_FRAGMENT, 

], 

args: { 

if: { 

type: new GraphQLNonNull(GraphQLBoolean), 

description: 'Included when true.', 

}, 

}, 

})
/** 

* The set of allowed directive location values. 

*/ 

export const DirectiveLocation = { 

// Request Definitions 

QUERY: 'QUERY', 

MUTATION: 'MUTATION', 

SUBSCRIPTION: 'SUBSCRIPTION', 

FIELD: 'FIELD', 

FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', 

FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', 

INLINE_FRAGMENT: 'INLINE_FRAGMENT', 

// Type System Definitions 

SCHEMA: 'SCHEMA', 

SCALAR: 'SCALAR', 

OBJECT: 'OBJECT', 

FIELD_DEFINITION: 'FIELD_DEFINITION', 

ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', 

INTERFACE: 'INTERFACE', 

UNION: 'UNION', 

ENUM: 'ENUM', 

ENUM_VALUE: 'ENUM_VALUE', 

INPUT_OBJECT: 'INPUT_OBJECT', 

INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', 

}

🤩
We can put directive
everywhere!
How to declare a
directive?
# GraphQL Schema 

directive @dateFormat(format: String!) on FIELD | FIELD_DEFINITION
How to use it?
I can use my own
directive 😎
But it doesn't work 😓
I need a directive
resolver!
Wait...
How to define a
directive resolver?
Not supported 😨
Let's take a look to a
resolver signature
Logging info...
{ fieldName: 'birthDate',
fieldNodes:
[ { kind: 'Field',
alias: null,
name: [Object],
arguments: [],
directives: [Array],
selectionSet: null,
loc: [Object] } ],
returnType: DateTime,
parentType: Human,
path:
{ prev: { prev: undefined, key: 'character' },
key: 'birthDate' },
schema:
GraphQLSchema {
_queryType: Query,
_mutationType: Mutation,
_subscriptionType: Subscription,
_directives:
[ [GraphQLDirective],
[GraphQLDirective],
[GraphQLDirective],
[GraphQLDirective] ],
astNode:
{ kind: 'SchemaDefinition',
SPOTED
[ { kind: 'Directive',
name: { kind: 'Name', value: 'dateFormat', loc: [Object] },
arguments: [ [Object] ],
loc: { start: 37, end: 62 } } ]
Let's write a directive
resolver!
import format from 'date-fns/format' 



const resolvers = { 

Character: { 

birthDate(obj, args, context, info) { 

const directive = info.fieldNodes[0].directives.find( 

directive => directive.name.value === 'dateFormat', 

) 

if (directive) { 

const formatArg = directive.arguments.find( 

arg => arg.name.value === 'format', 

) 

return formatDate(obj.birthDate, formatArg.value.value) 

} 

return obj.birthDate 

}, 

} 

}
I can use my own
directive and it works 😎
But it is not generic 😓
Introducing
graphql-directive
import { buildSchema } from 'graphql' 

import { addDirectiveResolveFunctionsToSchema } from 'graphql-directive' 

import format from 'date-fns/format' 



// Schema 

const schema = buildSchema(` 

directive @dateFormat(format: String) on FIELD_DEFINITION | FIELD 

`) 



// Resolver 

addDirectiveResolveFunctionsToSchema(schema, { 

async dateFormat(resolve, source, args) { 

const value = await resolve() 

return format(new Date(value), args.format) 

}, 

})
graphql-directive
•Easy to use
•Supports FIELD and FIELD_DEFINITION
locations
•Gives new power 🚀
Wait, I use it in my project
and it is random 🤔
The problem
query { 

myField @upperCase 

}
Query
Apollo Cache
{ 

"myField": "MYRESULT" 

}
With directive
query { 

myField
}
{ 

"myField": "myResult" 

}
Without directive
Same result 😱
The fix
query { 

myField @upperCase 

}
Query
Apollo Cache
{ 

"myField@upperCase": "MYRESULT" 

}
With directive
query { 

myField
}
{ 

"myField": "myResult" 

}
Without directive
Include directive
in cache key ✨
THANKS
I will tweet slides after the talk @neoziro

Contenu connexe

Tendances

Javascript Function
Javascript FunctionJavascript Function
Javascript Functionxxbeta
 
Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Platonov Sergey
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)hhliu
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methodsphil_nash
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Javascript function
Javascript functionJavascript function
Javascript functionLearningTech
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.Russell Childs
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphismmohamed sikander
 
How to practice functional programming in react
How to practice functional programming in reactHow to practice functional programming in react
How to practice functional programming in reactNetta Bondy
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)Ritika Sharma
 

Tendances (20)

Javascript Function
Javascript FunctionJavascript Function
Javascript Function
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Cquestions
Cquestions Cquestions
Cquestions
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
 
c programming
c programmingc programming
c programming
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Javascript function
Javascript functionJavascript function
Javascript function
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphism
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
How to practice functional programming in react
How to practice functional programming in reactHow to practice functional programming in react
How to practice functional programming in react
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 

Similaire à Extend GraphQL with directives

Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto UniversitySC5.io
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Introzhang tao
 
"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero Parviainen"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero ParviainenFwdays
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-CNissan Tsafrir
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to GriffonJames Williams
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)Jerome Eteve
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced FunctionsWebStackAcademy
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docxassignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docxssuser562afc1
 
How Does Kubernetes Build OpenAPI Specifications?
How Does Kubernetes Build OpenAPI Specifications?How Does Kubernetes Build OpenAPI Specifications?
How Does Kubernetes Build OpenAPI Specifications?reallavalamp
 
Creating Gradle Plugins - Oredev
Creating Gradle Plugins - OredevCreating Gradle Plugins - Oredev
Creating Gradle Plugins - OredevAnnyce Davis
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
 

Similaire à Extend GraphQL with directives (20)

Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero Parviainen"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero Parviainen
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to Griffon
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docxassignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
 
How Does Kubernetes Build OpenAPI Specifications?
How Does Kubernetes Build OpenAPI Specifications?How Does Kubernetes Build OpenAPI Specifications?
How Does Kubernetes Build OpenAPI Specifications?
 
Specs2
Specs2Specs2
Specs2
 
Creating Gradle Plugins - Oredev
Creating Gradle Plugins - OredevCreating Gradle Plugins - Oredev
Creating Gradle Plugins - Oredev
 
Java
JavaJava
Java
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
 

Dernier

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile EnvironmentVictorSzoltysek
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 

Dernier (20)

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

Extend GraphQL with directives

  • 2. I am Greg Bergé JavaScript, React & GraphQL trainer @neoziro ! github.com/neoziro " smooth-code.com#
  • 4. What is a directive?
  • 8. @include / @skip •Query directive •Can be used on fields and fragments •Control the scope of query using a parameter
  • 9. query Person($includeFilms: Boolean = false) { 
 person(personID: 1) { 
 name 
 height 
 mass 
 filmConnection(first: 10) @include(if: $includeFilms) { 
 edges { 
 node { 
 title 
 } 
 } 
 } 
 } 
 }
  • 10. query Person($skipFilms: Boolean = false) { 
 person(personID: 1) { 
 name 
 height 
 mass 
 filmConnection(first: 10) @skip(if: $skipFilms) { 
 edges { 
 node { 
 title 
 } 
 } 
 } 
 } 
 }
  • 11.
  • 12.
  • 13. @deprecated •Schema directive •Can be used on field definitions and enums •Marks an element of a GraphQL schema as no longer supported
  • 14. type Book { 
 name: String 
 longName: String @deprecated(reason: "use name instead") 
 }
  • 15.
  • 16.
  • 17. I love it 🤩 I want to create directives!
  • 19. •Resolved server-side → less computation on client •Most of GraphQL clients cache queries → avoid computation •Declarative → understand code by reading query
  • 20. query { 
 user { 
 name @upperCase 
 } 
 } Text Formatting
  • 21. Date Formatting query { 
 user { 
 birthDate @dateFormat(format: "DD/MM/YYYY") 
 } 
 }
  • 22. Restrictions type User { 
 privateNote: String @requireAuth 
 }
  • 24.
  • 25. 😒
  • 26.
  • 27. 🤔
  • 28.
  • 30.
  • 34. /** 
 * Used to conditionally include fields or fragments. 
 */ 
 export const GraphQLIncludeDirective = new GraphQLDirective({ 
 name: 'include', 
 description: 
 'Directs the executor to include this field or fragment only when ' + 
 'the `if` argument is true.', 
 locations: [ 
 DirectiveLocation.FIELD, 
 DirectiveLocation.FRAGMENT_SPREAD, 
 DirectiveLocation.INLINE_FRAGMENT, 
 ], 
 args: { 
 if: { 
 type: new GraphQLNonNull(GraphQLBoolean), 
 description: 'Included when true.', 
 }, 
 }, 
 })
  • 35. /** 
 * The set of allowed directive location values. 
 */ 
 export const DirectiveLocation = { 
 // Request Definitions 
 QUERY: 'QUERY', 
 MUTATION: 'MUTATION', 
 SUBSCRIPTION: 'SUBSCRIPTION', 
 FIELD: 'FIELD', 
 FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', 
 FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', 
 INLINE_FRAGMENT: 'INLINE_FRAGMENT', 
 // Type System Definitions 
 SCHEMA: 'SCHEMA', 
 SCALAR: 'SCALAR', 
 OBJECT: 'OBJECT', 
 FIELD_DEFINITION: 'FIELD_DEFINITION', 
 ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', 
 INTERFACE: 'INTERFACE', 
 UNION: 'UNION', 
 ENUM: 'ENUM', 
 ENUM_VALUE: 'ENUM_VALUE', 
 INPUT_OBJECT: 'INPUT_OBJECT', 
 INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', 
 }

  • 36. 🤩 We can put directive everywhere!
  • 37. How to declare a directive?
  • 38. # GraphQL Schema 
 directive @dateFormat(format: String!) on FIELD | FIELD_DEFINITION
  • 39. How to use it?
  • 40.
  • 41. I can use my own directive 😎
  • 42.
  • 43. But it doesn't work 😓
  • 44. I need a directive resolver!
  • 46. How to define a directive resolver?
  • 48. Let's take a look to a resolver signature
  • 49.
  • 51. { fieldName: 'birthDate', fieldNodes: [ { kind: 'Field', alias: null, name: [Object], arguments: [], directives: [Array], selectionSet: null, loc: [Object] } ], returnType: DateTime, parentType: Human, path: { prev: { prev: undefined, key: 'character' }, key: 'birthDate' }, schema: GraphQLSchema { _queryType: Query, _mutationType: Mutation, _subscriptionType: Subscription, _directives: [ [GraphQLDirective], [GraphQLDirective], [GraphQLDirective], [GraphQLDirective] ], astNode: { kind: 'SchemaDefinition', SPOTED
  • 52. [ { kind: 'Directive', name: { kind: 'Name', value: 'dateFormat', loc: [Object] }, arguments: [ [Object] ], loc: { start: 37, end: 62 } } ]
  • 53. Let's write a directive resolver!
  • 54. import format from 'date-fns/format' 
 
 const resolvers = { 
 Character: { 
 birthDate(obj, args, context, info) { 
 const directive = info.fieldNodes[0].directives.find( 
 directive => directive.name.value === 'dateFormat', 
 ) 
 if (directive) { 
 const formatArg = directive.arguments.find( 
 arg => arg.name.value === 'format', 
 ) 
 return formatDate(obj.birthDate, formatArg.value.value) 
 } 
 return obj.birthDate 
 }, 
 } 
 }
  • 55.
  • 56. I can use my own directive and it works 😎
  • 57. But it is not generic 😓
  • 58.
  • 60.
  • 61. import { buildSchema } from 'graphql' 
 import { addDirectiveResolveFunctionsToSchema } from 'graphql-directive' 
 import format from 'date-fns/format' 
 
 // Schema 
 const schema = buildSchema(` 
 directive @dateFormat(format: String) on FIELD_DEFINITION | FIELD 
 `) 
 
 // Resolver 
 addDirectiveResolveFunctionsToSchema(schema, { 
 async dateFormat(resolve, source, args) { 
 const value = await resolve() 
 return format(new Date(value), args.format) 
 }, 
 })
  • 62. graphql-directive •Easy to use •Supports FIELD and FIELD_DEFINITION locations •Gives new power 🚀
  • 63. Wait, I use it in my project and it is random 🤔
  • 65. query { 
 myField @upperCase 
 } Query Apollo Cache { 
 "myField": "MYRESULT" 
 } With directive query { 
 myField } { 
 "myField": "myResult" 
 } Without directive Same result 😱
  • 67. query { 
 myField @upperCase 
 } Query Apollo Cache { 
 "myField@upperCase": "MYRESULT" 
 } With directive query { 
 myField } { 
 "myField": "myResult" 
 } Without directive Include directive in cache key ✨
  • 68.
  • 69. THANKS I will tweet slides after the talk @neoziro