Current Specification Directives
1. @deprecated
A field or a whole type can be marked as deprecated, meaning that it should no longer be utilized, by using the @deprecated directive. To supply more details regarding the reasons behind the field or type’s deprecation, an optional reason parameter is required.
graphql
type Product {
id: ID!
name: String!
price: Float! @deprecated(reason: "Use 'unitPrice' instead")
unitPrice: Float!
}
Explanation: In this example, the price field is marked as deprecated, and a reason is provided to explain why it’s deprecated. Developers querying this schema will receive a warning that price is deprecated and should use unitPrice instead.
2. @skip
A field in the response can be conditionally skipped using the @skip directive if a Boolean condition is met. The field is skipped if the condition evaluates to true; if otherwise, it is included in the answer.
graphql
query GetUserDetails($skipAdminDetails: Boolean!) {
user(id: "123") {
id
name
isAdmin @skip(if: $skipAdminDetails)
adminDetails {
role
permissions
}
}
}
Explanation: In this query, if the skipAdminDetails variable is true, the isAdmin field will be skipped in the response. Otherwise, it will be included.
3. @include
A field in the response can be conditionally included using the @include directive in accordance with a Boolean condition. The field is included in the answer if the condition evaluates to true; if not, it is left out.
graphql
query GetUser($includeAddress: Boolean!) {
user {
id
name
address @include(if: $includeAddress) {
street
city
country
}
}
}
Explanation: In this query, the address field will be included in the response only if the includeAddress variable is true.
4. @specifiedBy
To define a URL that describes how a GraphQL type or interface behaves, use the @specifiedBy directive. It offers a link to outside documentation or specifications for more details on the type or interface.
graphql
scalar DateTime @specifiedBy(url: "https://graphql.org/learn/schema/#scalar-types")
Explanation: In this example, the DateTime scalar type is specified to be defined by the URL provided, which could lead to documentation or specifications explaining its behavior.
Directives in GraphQL
In GraphQL, directives are a powerful tool used to control the execution of queries and mutations. They provide a way to dynamically modify the structure and shape of GraphQL operations, enabling more flexibility and control over the data fetching process.
In this article, We will learn about what is Directives, their types along with some Current Specification Directives with the help of examples, and so on.