-
Notifications
You must be signed in to change notification settings - Fork 242
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
docs: custom directive examples and docs page #982
Merged
Merged
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f66848a
docs: define custom directive and docs page
brainrepo e4092c9
docs: example change
brainrepo d9810b6
Docs: add more info
brainrepo 8b5c356
docs: add example link
brainrepo 5a1f6f1
docs: typos
brainrepo 9e6ba09
docs: change redaction strategy
brainrepo 02159f2
docs: nits
brainrepo f78febb
add sidebar link and graphql tools version
brainrepo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
# Custom directive | ||
|
||
We might need to customise our schema by decorating parts of it or operations to add new reusable features to these elements. | ||
To do that, we can use a GraphQL concept called **Directive**. | ||
|
||
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. | ||
Directives can be used to modify the behaviour of fields, arguments, or types in your schema. | ||
|
||
A custom directive is composed of 2 parts: | ||
- schema definitions | ||
- transformer | ||
|
||
## Schema Definition | ||
Let's explore the custom directive creation process by creating a directive to redact some fields value, hiding a phone number or an email. | ||
|
||
First of all, we must define the schema | ||
|
||
```js | ||
const schema = ` | ||
directive @redact(find: String) on FIELD_DEFINITION | ||
|
||
type Document { | ||
excerpt: String! @redact(find: "email") | ||
text: String! @redact(find: "phone") | ||
} | ||
|
||
type Query { | ||
documents: [Document] | ||
}` | ||
``` | ||
|
||
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. | ||
|
||
``` | ||
directive @redact(find: String) on FIELD_DEFINITION | ||
``` | ||
|
||
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). | ||
|
||
## Transformer | ||
|
||
Every directive needs its transformer. | ||
A transformer is a function that takes an existing schema and applies the modifications to the schema and resolvers. | ||
|
||
To simplify the process of creating a transformer, we use the `mapSchema` function from the `@graphql-tools` library. | ||
|
||
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. | ||
|
||
```js | ||
const { mapSchema, getDirective, MapperKind } = require('@graphql-tools/utils') | ||
|
||
// Define the regexp | ||
const PHONE_REGEXP = /(?:\+?\d{2}[ -]?\d{3}[ -]?\d{5}|\d{4})/g; | ||
const EMAIL_REGEXP = /([^\s@])+@[^\s@]+\.[^\s@]+/g | ||
|
||
const redactionSchemaTransformer = (schema) => mapSchema(schema, { | ||
// When parsing the schema we find a FIELD | ||
[MapperKind.FIELD]: fieldConfig => { | ||
|
||
// Get the directive information | ||
const redactDirective = getDirective(schema, fieldConfig, "redact")?.[0] | ||
if (redactDirective) { | ||
// Extract the find attribute from the directive, this attribute will | ||
// be used to chose which replace strategy adopt | ||
const { find } = redactDirective | ||
// Create a new resolver | ||
fieldConfig.resolve = async (obj, _args, _ctx, info) => { | ||
// Extract the value of the property we want redact | ||
// getting the field name from the info parameter. | ||
const value = obj[info.fieldName] | ||
|
||
// Apply the redaction strategy and return the result | ||
switch (find) { | ||
case 'email': | ||
return value.replace(EMAIL_REGEXP, '****@*****.***') | ||
case 'phone': | ||
return value.replace(PHONE_REGEXP, m => '*'.repeat(m.length)) | ||
default: | ||
return value | ||
} | ||
} | ||
} | ||
} | ||
}) | ||
``` | ||
|
||
As you can see in the new resolver function as props, we receive the `current object`, the `arguments`, the `context` and the `info`. | ||
|
||
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 | ||
|
||
- fieldNodes | ||
- returnType | ||
- parentType | ||
- operation | ||
|
||
## Generate executable schema | ||
To make our custom directive work, we must first create an executable schema required by the `mapSchema` function to change the resolvers' behaviour. | ||
|
||
```js | ||
const executableSchema = makeExecutableSchema({ | ||
typeDefs: schema, | ||
resolvers | ||
}) | ||
``` | ||
|
||
## Apply transformations to the executable schema | ||
|
||
Now it is time to transform our schema. | ||
|
||
```js | ||
const newSchema = redactionSchemaTransformer(executableSchema) | ||
``` | ||
|
||
and to register mercurius inside fastify | ||
|
||
```js | ||
app.register(mercurius, { | ||
schema: newSchema, | ||
graphiql: true, | ||
}) | ||
``` | ||
|
||
## Example | ||
|
||
We have a runnable example on "example/custom-directive.js" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
'use strict' | ||
|
||
const Fastify = require('fastify') | ||
const mercurius = require('..') | ||
const { makeExecutableSchema } = require('@graphql-tools/schema') | ||
const { mapSchema, getDirective, MapperKind } = require('@graphql-tools/utils') | ||
|
||
const app = Fastify() | ||
|
||
const resolvers = { | ||
Query: { | ||
documents: async (_, _obj, _ctx) => { | ||
return [{ | ||
excerpt: 'Proin info@mercurius.dev rutrum pulvinar lectus sed placerat.', | ||
text: 'Proin 33 222-33355 rutrum pulvinar lectus sed placerat.' | ||
}] | ||
} | ||
} | ||
} | ||
|
||
// Define the executable schema | ||
const schema = makeExecutableSchema({ | ||
typeDefs: ` | ||
# Define the directive schema | ||
directive @redact(find: String) on FIELD_DEFINITION | ||
|
||
type Document { | ||
excerpt: String! @redact(find: "email") | ||
text: String! @redact(find: "phone") | ||
} | ||
|
||
type Query { | ||
documents: [Document] | ||
} | ||
`, | ||
resolvers | ||
}) | ||
|
||
const PHONE_REGEXP = /(?:\+?\d{2}[ -]?\d{3}[ -]?\d{5}|\d{4})/g | ||
const EMAIL_REGEXP = /([^\s@])+@[^\s@]+\.[^\s@]+/g | ||
|
||
const redactionSchemaTransformer = (schema) => mapSchema(schema, { | ||
[MapperKind.OBJECT_FIELD]: fieldConfig => { | ||
const redactDirective = getDirective(schema, fieldConfig, 'redact')?.[0] | ||
|
||
if (redactDirective) { | ||
brainrepo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const { find } = redactDirective | ||
|
||
fieldConfig.resolve = async (obj, _args, ctx, info) => { | ||
const value = obj[info.fieldName] | ||
|
||
if (!ctx.redact) { | ||
return document | ||
} | ||
|
||
switch (find) { | ||
case 'email': | ||
return value.replace(EMAIL_REGEXP, '****@*****.***') | ||
case 'phone': | ||
return value.replace(PHONE_REGEXP, m => '*'.repeat(m.length)) | ||
default: | ||
return value | ||
} | ||
} | ||
} | ||
} | ||
}) | ||
|
||
// Register mercurius and run it | ||
app.register(mercurius, { | ||
schema: redactionSchemaTransformer(schema), | ||
context: (request, reply) => { | ||
return { | ||
redact: true | ||
} | ||
}, | ||
graphiql: true | ||
}) | ||
|
||
app.listen({ port: 3000 }) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should document somewhere what version of graphql-tools this guide refers to
graphql-tools
.I would also prefer to not use graphql-tools here or show both examples.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I opted for the use of graphql tools because, being an example, I wanted to keep it as lean as possible. Inserting a code snippet (generic) for creating an executable schema or for decorating resolvers, risks being misleading for the purpose of the example, making it more complex to understand and also to reuse.
Instead, if I adopt the strategy to modify the schema ad hoc for the redact directive, we might reduce the amount of code but make the example hard to reuse.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree with Mauro, we have discussed in detail and replicating the features coming from the graphql-tools library for the sake of this example is just not worth it, and quite frankly in general it's not worth it. Nevertheless since this issue comes up quite often, we'll come up with a couple of ideas that we'll open as issues in this repo:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, I have provided a more detailed argument on this issue. #989