|
| 1 | +--- |
| 2 | +sidebar_position: 8 |
| 3 | +--- |
| 4 | + |
| 5 | +# Custom directive |
| 6 | + |
| 7 | +We might need to customise our schema by decorating parts of it or operations to add new reusable features to these elements. |
| 8 | +To do that, we can use a GraphQL concept called **Directive**. |
| 9 | + |
| 10 | +A GraphQL directive is a special syntax used to provide additional information to the GraphQL execution engine about how to process a query, mutation, or schema definition. |
| 11 | +Directives can be used to modify the behaviour of fields, arguments, or types in your schema. |
| 12 | + |
| 13 | +A custom directive is composed of 2 parts: |
| 14 | + |
| 15 | +- schema definitions |
| 16 | +- transformer |
| 17 | + |
| 18 | +## Schema Definition |
| 19 | + |
| 20 | +Let's explore the custom directive creation process by creating a directive to redact some fields value, hiding a phone number or an email. |
| 21 | + |
| 22 | +First of all, we must define the schema |
| 23 | + |
| 24 | +```js |
| 25 | +const schema = ` |
| 26 | + directive @redact(find: String) on FIELD_DEFINITION |
| 27 | + |
| 28 | + type Document { |
| 29 | + excerpt: String! @redact(find: "email") |
| 30 | + text: String! @redact(find: "phone") |
| 31 | + } |
| 32 | +
|
| 33 | + type Query { |
| 34 | + documents: [Document] |
| 35 | + }`; |
| 36 | +``` |
| 37 | + |
| 38 | +To define a custom directive, we must use the directive keyword, followed by its name prefixed by a `@`, the arguments (if any), and the locations where it can be applied. |
| 39 | + |
| 40 | +``` |
| 41 | +directive @redact(find: String) on FIELD_DEFINITION |
| 42 | +``` |
| 43 | + |
| 44 | +According to the graphql specs the directive can be applied in multiple locations. See the list on [the GraphQL spec page](https://spec.graphql.org/October2021/#sec-Type-System.Directives). |
| 45 | + |
| 46 | +## Transformer |
| 47 | + |
| 48 | +Every directive needs its transformer. |
| 49 | +A transformer is a function that takes an existing schema and applies the modifications to the schema and resolvers. |
| 50 | + |
| 51 | +To simplify the process of creating a transformer, we use the `mapSchema` function from the `@graphql-tools` library. |
| 52 | +In this example we are refering to [graphqltools 8.3.20](https://www.npmjs.com/package/graphql-tools/v/8.3.20) |
| 53 | + |
| 54 | +The `mapSchema` function applies each callback function to the corresponding type definition in the schema, creating a new schema with the modified type definitions. The function also provides access to the field resolvers of each object type, allowing you to alter the behaviour of the fields in the schema. |
| 55 | + |
| 56 | +```js |
| 57 | +const { mapSchema, getDirective, MapperKind } = require("@graphql-tools/utils"); |
| 58 | + |
| 59 | +// Define the regexp |
| 60 | +const PHONE_REGEXP = /(?:\+?\d{2}[ -]?\d{3}[ -]?\d{5}|\d{4})/g; |
| 61 | +const EMAIL_REGEXP = /([^\s@])+@[^\s@]+\.[^\s@]+/g; |
| 62 | + |
| 63 | +const redactionSchemaTransformer = schema => |
| 64 | + mapSchema(schema, { |
| 65 | + // When parsing the schema we find a FIELD |
| 66 | + [MapperKind.FIELD]: fieldConfig => { |
| 67 | + // Get the directive information |
| 68 | + const redactDirective = getDirective(schema, fieldConfig, "redact")?.[0]; |
| 69 | + if (redactDirective) { |
| 70 | + // Extract the find attribute from the directive, this attribute will |
| 71 | + // be used to chose which replace strategy adopt |
| 72 | + const { find } = redactDirective; |
| 73 | + // Create a new resolver |
| 74 | + fieldConfig.resolve = async (obj, _args, _ctx, info) => { |
| 75 | + // Extract the value of the property we want redact |
| 76 | + // getting the field name from the info parameter. |
| 77 | + const value = obj[info.fieldName]; |
| 78 | + |
| 79 | + // Apply the redaction strategy and return the result |
| 80 | + switch (find) { |
| 81 | + case "email": |
| 82 | + return value.replace(EMAIL_REGEXP, "****@*****.***"); |
| 83 | + case "phone": |
| 84 | + return value.replace(PHONE_REGEXP, m => "*".repeat(m.length)); |
| 85 | + default: |
| 86 | + return value; |
| 87 | + } |
| 88 | + }; |
| 89 | + } |
| 90 | + }, |
| 91 | + }); |
| 92 | +``` |
| 93 | +
|
| 94 | +As you can see in the new resolver function as props, we receive the `current object`, the `arguments`, the `context` and the `info`. |
| 95 | +
|
| 96 | +Using the field name exposed by the `info` object, we get the field value from the `obj` object, object that contains lots of helpful informations like |
| 97 | +
|
| 98 | +- fieldNodes |
| 99 | +- returnType |
| 100 | +- parentType |
| 101 | +- operation |
| 102 | +
|
| 103 | +## Generate executable schema |
| 104 | +
|
| 105 | +To make our custom directive work, we must first create an executable schema required by the `mapSchema` function to change the resolvers' behaviour. |
| 106 | +
|
| 107 | +```js |
| 108 | +const executableSchema = makeExecutableSchema({ |
| 109 | + typeDefs: schema, |
| 110 | + resolvers, |
| 111 | +}); |
| 112 | +``` |
| 113 | +
|
| 114 | +## Apply transformations to the executable schema |
| 115 | +
|
| 116 | +Now it is time to transform our schema. |
| 117 | +
|
| 118 | +```js |
| 119 | +const newSchema = redactionSchemaTransformer(executableSchema); |
| 120 | +``` |
| 121 | +
|
| 122 | +and to register mercurius inside fastify |
| 123 | +
|
| 124 | +```js |
| 125 | +app.register(mercurius, { |
| 126 | + schema: newSchema, |
| 127 | + graphiql: true, |
| 128 | +}); |
| 129 | +``` |
| 130 | +
|
| 131 | +## Example |
| 132 | +
|
| 133 | +We have a runnable example on "example/custom-directive.js" |
| 134 | +
|
| 135 | +## Federation and Custom Directives |
| 136 | +
|
| 137 | +Because schemas involved in GraphQL federation may use special syntax (e.g. `extends`) and custom directives (e.g. `@key`) that are not available in non-federated schemas, there are some extra steps that need to be run to generate the executable schema, involving the use of `buildFederationSchema` from the `@mercuriusjs/federation` library and `printSchemaWithDirectives` from the `@graphql-tools/utils` library. |
| 138 | +
|
| 139 | +To see how this works, we will go through another example where we create a custom directive to uppercase the value of a field in a federated environment. |
| 140 | +
|
| 141 | +### Schema Definition |
| 142 | +
|
| 143 | +The schema definition is equal to the one used in the previous example. We add the `@upper` directive and we decorate the `name` field with it. |
| 144 | +
|
| 145 | +```js |
| 146 | +const schema = ` |
| 147 | + directive @upper on FIELD_DEFINITION |
| 148 | +
|
| 149 | + extend type Query { |
| 150 | + me: User |
| 151 | + } |
| 152 | +
|
| 153 | + type User @key(fields: "id") { |
| 154 | + id: ID! |
| 155 | + name: String @upper |
| 156 | + username: String |
| 157 | + }`; |
| 158 | +``` |
| 159 | +
|
| 160 | +### Transformer |
| 161 | +
|
| 162 | +The transformer follows the same approach used in the previous example. We declare the uppercase transform function and apply it to the field resolver if they have the `@upper` directive. |
| 163 | +
|
| 164 | +```js |
| 165 | +const { mapSchema, getDirective, MapperKind } = require("@graphql-tools/utils"); |
| 166 | + |
| 167 | +const uppercaseTransformer = schema => |
| 168 | + mapSchema(schema, { |
| 169 | + [MapperKind.FIELD]: fieldConfig => { |
| 170 | + const upperDirective = getDirective(schema, fieldConfig, "upper")?.[0]; |
| 171 | + if (upperDirective) { |
| 172 | + fieldConfig.resolve = async (obj, _args, _ctx, info) => { |
| 173 | + const value = obj[info.fieldName]; |
| 174 | + return typeof value === "string" ? value.toUpperCase() : value; |
| 175 | + }; |
| 176 | + } |
| 177 | + }, |
| 178 | + }); |
| 179 | +``` |
| 180 | +
|
| 181 | +### Generate executable schema |
| 182 | +
|
| 183 | +This section starts to be different. First, we need to create the federation schema using the `buildFederationSchema` function from the `@mercuriusjs/federation` library; then, we can use the `makeExecutableSchema` function from the `@graphql-tools/schema` library to create the executable schema. |
| 184 | +Using the `printSchemaWithDirectives`, we can get the schema with all the custom directives applied, and using the `mergeResolvers` function from the `@graphql-tools/merge` library, we can merge the resolvers from the federation schema and the ones we defined. |
| 185 | +
|
| 186 | +Following these steps, we can create our executable schema. |
| 187 | +
|
| 188 | +```js |
| 189 | +const { buildFederationSchema } = require("@mercuriusjs/federation"); |
| 190 | +const { |
| 191 | + printSchemaWithDirectives, |
| 192 | + getResolversFromSchema, |
| 193 | +} = require("@graphql-tools/utils"); |
| 194 | +const { mergeResolvers } = require("@graphql-tools/merge"); |
| 195 | +const { makeExecutableSchema } = require("@graphql-tools/schema"); |
| 196 | + |
| 197 | +const federationSchema = buildFederationSchema(schema); |
| 198 | + |
| 199 | +const executableSchema = makeExecutableSchema({ |
| 200 | + typeDefs: printSchemaWithDirectives(federationSchema), |
| 201 | + resolvers: mergeResolvers([ |
| 202 | + getResolversFromSchema(federationSchema), |
| 203 | + resolvers, |
| 204 | + ]), |
| 205 | +}); |
| 206 | +``` |
| 207 | +
|
| 208 | +### Apply transformations to the executable schema |
| 209 | +
|
| 210 | +To apply the transformation, we have to use the mercurius plugin and pass the options: |
| 211 | +
|
| 212 | +- **schema**: with the executableSchema already generated |
| 213 | +- **schemaTransforms**: with the transformer functions |
| 214 | +
|
| 215 | +```js |
| 216 | +app.register(mercurius, { |
| 217 | + schema: executableSchema, |
| 218 | + schemaTransforms: [uppercaseTransformer], |
| 219 | + graphiql: true, |
| 220 | +}); |
| 221 | +``` |
| 222 | +
|
| 223 | +### Example |
| 224 | +
|
| 225 | +We have a runnable example in the Federation repo that you can find here [examples/withCustomDirectives.js](https://github.com/mercurius-js/mercurius-federation/tree/main/examples/withCustomDirectives.js). |
0 commit comments