Directive
The way to add extra directive. Learn about Directives
Specification
There are three places where you can add directives:
- on operation root
- on field
- on inline fragment
Operation
TIP
You need to use full spread query builder if you want to use directives
. It means you need to add a empty variable definition to the query. The builder will automatically ignore the empty variable.
ts
const query = gqfn('query', {}, [
'time'
], $ => [
['@cache', { rule: 'cache-first', maxAge: 3600 }],
])
graphql
query @cache(rule: "cache-first", maxAge: 3600) {
time
}
Some times you need to use variables in the directive, for example:
ts
const query = gqfn('query', {
maxAge: 'Int!',
}, [
'time'
], $ => [
['@cache', { rule: 'cache-first', maxAge: $.maxAge }],
])
graphql
query ($maxAge: Int!) @cache(rule: "cache-first", maxAge: $maxAge) {
time
}
Field
ts
const query = gqfn('query', {}, [
{
now: $ => $(true, [
['@skip', { if: false }],
]),
},
])
graphql
{
now @skip(if: false)
}
Also you can use variables in the directive:
ts
const query = gqfn('query', { withTime: 'Boolean!' }, [
{
now: $ => $(true, [
['@include', { if: $.withTime }],
]),
},
])
graphql
query ($withTime: Boolean!) {
now @include(if: $withTime)
}
Inline Fragment
It is same to field, for example:
ts
const query = gqfn('query', { withDate: 'Boolean!' }, [
{
users: $ => $([
'id',
'name',
'email',
{
'...': $ => $([
'createdAt',
'updatedAt',
], [
['@include', { if: $.withDate }],
]),
},
]),
},
])
graphql
query ($withDate: Boolean!) {
users {
id
name
email
... @include(if: $withDate) {
createdAt
updatedAt
}
}
}
Type Definition
ts
export type Directives = Array<Directive>
export type Directive = [`@${string}`, { [key: string]: any }]