Skip to content
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 8 commits into from
May 1, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions docs/custom-directive.md
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')
Copy link
Collaborator

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.

Copy link
Contributor Author

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.

Copy link
Collaborator

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:

  • one specific to this request, a way built-into mercurius (or a plugin) to make it easier to define and attach custom directives
  • one generic about creating a new library alternative to graphql-tools with similar features

Copy link
Contributor Author

@brainrepo brainrepo Apr 28, 2023

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


// 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"
80 changes: 80 additions & 0 deletions examples/custom-directive.js
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) {
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 })