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 5 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
130 changes: 130 additions & 0 deletions docs/custom-directive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# 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.
For example, 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 specific word.**

First of all, we must define the schema

```js
const schema = `
# Define the directive schema
directive @redact(find: String) on FIELD_DEFINITION

type Document {
id: String!
text: String! @redact(find: "password")
}

type Query {
document: 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
```

The directive can be applied in multiple locations.

- **QUERY:** Location adjacent to a query operation.
- **MUTATION:** Location adjacent to a mutation operation.
- **SUBSCRIPTION:** Location adjacent to a subscription operation.
- **FIELD:** Location adjacent to a field.
- **FRAGMENT_DEFINITION:** Location adjacent to a fragment definition.
- **FRAGMENT_SPREAD:** Location adjacent to a fragment spread.
- **INLINE_FRAGMENT:** Location adjacent to an inline fragment.
- **SCALAR:** Location adjacent to a scalar definition.
- **OBJECT:** Location adjacent to an object type definition.
- **FIELD_DEFINITION:** Location adjacent to a field definition.
- **ARGUMENT_DEFINITION:** Location adjacent to an argument definition.
- **INTERFACE:** Location adjacent to an interface definition.
- **UNION:** Location adjacent to a union definition.
- **ENUM:** Location adjacent to an enum definition.
- **ENUM_VALUE:** Location adjacent to an enum value definition.
- **INPUT_OBJECT:** Location adjacent to an input object type definition.
- **INPUT_FIELD_DEFINITION:** Location adjacent to an input object field definition

## 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


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 te directive
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]
return value.replace(find, '**********')
}
}
}
})
```

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"
69 changes: 69 additions & 0 deletions examples/custom-directive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
'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: {
document: async (_, _obj, _ctx) => {
return {
id: '1',
text: 'Proin password 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 {
id: String!
text: String! @redact(find: "password")
}

type Query {
document: Document
}
`,
resolvers
})

// Define directive schema resolver
const redactionSchemaTransformer = (schema) => mapSchema(schema, {
// When parsing the schema we find a FIELD
[MapperKind.OBJECT_FIELD]: fieldConfig => {
// Get the directive information
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.redaction) {
return document
}
return value.replace(find, '**********')
}
}
}
})

// Register mercurius and run it
app.register(mercurius, {
schema: redactionSchemaTransformer(schema),
context: (request, reply) => {
return {
redaction: true
}
},
graphiql: true
})

app.listen({ port: 3000 })