Skip to content

Commit 9619dfd

Browse files
committed
feat: new website for mercurius
1 parent ac5030a commit 9619dfd

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+21379
-1
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ dist
106106

107107
# Docusaurus cache and generated files
108108
.docusaurus
109+
/build
109110

110111
# Serverless directories
111112
.serverless/
@@ -128,3 +129,7 @@ dist
128129
.yarn/build-state.yml
129130
.yarn/install-state.gz
130131
.pnp.*
132+
133+
134+
# MacOS
135+
.DS_Store

README.md

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,23 @@
1-
# website
1+
# website
2+
3+
## Installation
4+
5+
```
6+
npm install
7+
```
8+
9+
## Local Development
10+
11+
```
12+
npm run start
13+
```
14+
15+
## Build
16+
17+
```
18+
19+
npm run build
20+
21+
npm run serve
22+
23+
```

babel.config.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
3+
};

docs/guides/_category_.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"label": "Guides",
3+
"position": 1
4+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"label": "Batched Queries",
3+
"position": 9
4+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
---
2+
sidebar_position: 9
3+
---
4+
5+
# Batched Queries
6+
7+
Batched queries, like those sent by `apollo-link-batch-http` are supported by enabling the `allowBatchedQueries` option.
8+
9+
Instead a single query object, an array of queries is accepted, and the response is returned as an array of results. Errors are returned on a per query basis. Note that the response will not be returned until the slowest query has been executed.
10+
11+
Request:
12+
13+
```js
14+
[
15+
{
16+
operationName: "AddQuery",
17+
variables: { x: 1, y: 2 },
18+
query: "query AddQuery ($x: Int!, $y: Int!) { add(x: $x, y: $y) }",
19+
},
20+
{
21+
operationName: "DoubleQuery",
22+
variables: { x: 1 },
23+
query: "query DoubleQuery ($x: Int!) { add(x: $x, y: $x) }",
24+
},
25+
{
26+
operationName: "BadQuery",
27+
query: "query DoubleQuery ($x: Int!) {---", // Malformed Query
28+
},
29+
];
30+
```
31+
32+
Response:
33+
34+
```js
35+
[
36+
{
37+
data: { add: 3 },
38+
},
39+
{
40+
data: { add: 2 },
41+
},
42+
{
43+
errors: [{ message: "Bad Request" }],
44+
},
45+
];
46+
```
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"label": "Context",
3+
"position": 2
4+
}

docs/guides/context/context.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---
2+
sidebar_position: 2
3+
---
4+
5+
# Context
6+
7+
## Access app context in resolver
8+
9+
```js
10+
...
11+
const resolvers = {
12+
Query: {
13+
add: async (_, { x, y }, context) => {
14+
// do you need the request object?
15+
console.log(context.reply.request)
16+
return x + y
17+
}
18+
}
19+
}
20+
...
21+
```
22+
23+
### Build a custom GraphQL context object
24+
25+
```js
26+
...
27+
const resolvers = {
28+
Query: {
29+
me: async (obj, args, ctx) => {
30+
// access user_id in ctx
31+
console.log(ctx.user_id)
32+
}
33+
}
34+
}
35+
app.register(mercurius, {
36+
schema: makeExecutableSchema({ typeDefs, resolvers }),
37+
context: (request, reply) => {
38+
// Return an object that will be available in your GraphQL resolvers
39+
return {
40+
user_id: 1234
41+
}
42+
}
43+
})
44+
...
45+
```
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"label": "Custom Directive",
3+
"position": 8
4+
}
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
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

Comments
 (0)