Skip to content

Commit 3d1f0e9

Browse files
committed
feat: add support for FIELD and FIELD_DEFINITION directives
1 parent 380a6d1 commit 3d1f0e9

17 files changed

+5080
-0
lines changed

.babelrc

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"presets": [
3+
["env", {
4+
"targets": {
5+
"node": "6"
6+
}
7+
}]
8+
],
9+
"plugins": [
10+
"transform-class-properties",
11+
"transform-object-rest-spread"
12+
]
13+
}

.eslintignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules/
2+
lib/

.eslintrc.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
module.exports = {
2+
root: true,
3+
extends: ['airbnb-base', 'prettier'],
4+
parser: 'babel-eslint',
5+
parserOptions: {
6+
ecmaVersion: 8,
7+
sourceType: 'module',
8+
},
9+
env: {
10+
jest: true,
11+
},
12+
rules: {
13+
'class-methods-use-this': 'off',
14+
'no-param-reassign': 'off',
15+
'no-use-before-define': 'off',
16+
'import/prefer-default-export': 'off',
17+
},
18+
}
19+

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules/
2+
coverage/

.npmignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/*
2+
!/lib/*.js
3+
*.test.js

.prettierrc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"singleQuote": true,
3+
"trailingComma": "all",
4+
"semi": false
5+
}

.travis.yml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
language: node_js
2+
3+
node_js:
4+
- 6
5+
- 8
6+
7+
before_install:
8+
- curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.3.2
9+
- export PATH="$HOME/.yarn/bin:$PATH"
10+
11+
script:
12+
- yarn ci
13+
14+
notifications:
15+
email: false
16+
17+
cache:
18+
yarn: true
19+
directories:
20+
- "node_modules"

LICENSE

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright 2017 Smooth Code
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
# graphql-directives
2+
3+
[![Build Status][build-badge]][build]
4+
[![Code Coverage][coverage-badge]][coverage]
5+
[![version][version-badge]][package]
6+
[![MIT License][license-badge]][license]
7+
8+
GraphQL supports several directives: `@include`, `@skip` et `@deprecated`. This module opens a new dimension by giving you the possibility to define your custom directives.
9+
10+
Custom directives have a lot of use-cases:
11+
12+
* Formatting
13+
* Authentication
14+
* Introspection
15+
* ...
16+
17+
You can [learn more about directives in GraphQL documentation](http://graphql.org/learn/queries/#directives).
18+
19+
## Install
20+
21+
```sh
22+
npm install graphql-directives
23+
```
24+
25+
## Steps
26+
27+
### 1. Define a directive in schema
28+
29+
A directive must be defined in your schema, it can be done using the keyword `directive`:
30+
31+
```graphql
32+
directive @dateFormat(format: String) on FIELD | FIELD_DEFINITION
33+
```
34+
35+
This code defines a directive called `dateFormat` that accepts one argument `format` of type `String`. The directive can be used on `FIELD` (query) and `FIELD_DEFINITION` (schema).
36+
37+
**FIELD AND FIELD_DEFINITION are the only two directive locations supported.**
38+
39+
### 2. Add directive resolver
40+
41+
The second step consists in adding a resolver for the custom directive.
42+
43+
```js
44+
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directives'
45+
46+
// Attach a resolver map to schema
47+
addDirectiveResolveFunctionsToSchema(schema, {
48+
async dateFormat(resolve, source, args) {
49+
const value = await resolve()
50+
return format(new Date(value), args.format)
51+
},
52+
})
53+
```
54+
55+
### 3. Use directive in query
56+
57+
You can now use your directive either in schema or in query.
58+
59+
```js
60+
import { graphql } from 'graphql'
61+
62+
const QUERY = `{ publishDate @dateFormat(format: "DD-MM-YYYY") }`
63+
64+
const rootValue = { publishDate: '1997-06-12T00:00:00.000Z' }
65+
66+
graphql(schema, query, rootValue).then(response => {
67+
console.log(response.data) // { publishDate: '12-06-1997' }
68+
})
69+
```
70+
71+
## Usage
72+
73+
### addDirectiveResolveFunctionsToSchema(schema, resolverMap)
74+
75+
`addDirectiveResolveFunctionsToSchema` takes two arguments, a GraphQLSchema and a resolver map. It modifies the schema in place by attaching directive resolvers. Internally your resolvers are wrapped into another one.
76+
77+
```js
78+
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directives'
79+
80+
const resolverMap = {
81+
// Will be called when a @upperCase directive is applied to a field.
82+
async upperCase(resolve) {
83+
const value = await resolve()
84+
return value.toString().toUpperCase()
85+
},
86+
}
87+
88+
// Attach directive resolvers to schema.
89+
addDirectiveResolveFunctionsToSchema(schema, resolverMap)
90+
```
91+
92+
### Directive resolver function signature
93+
94+
Every directive resolver accepts five positional arguments:
95+
96+
```
97+
directiveName(resolve, obj, directiveArgs, context, info) { result }
98+
```
99+
100+
These arguments have the following conventional names and meanings:
101+
102+
1. `resolve`: Resolve is a function that returns the result of the directive field. For consistency, it always returns a promise resolved with the original field resolver.
103+
2. `obj`: The object that contains the result returned from the resolver on the parent field, or, in the case of a top-level `Query` field, the `rootValue` passed from the server configuration. This argument enables the nested nature of GraphQL queries.
104+
3. `directiveArgs`: An object with the arguments passed into the directive in the query or schema. For example, if the directive was called with `@dateFormat(format: "DD/MM/YYYY")`, the args object would be: `{ "format": "DD/MM/YYYY" }`.
105+
4. `context`: This is an object shared by all resolvers in a particular query, and is used to contain per-request state, including authentication information, [dataloader](https://github.com/facebook/dataloader) instances, and anything else that should be taken into account when resolving the query.
106+
5. `info`: This argument should only be used in advanced cases, but it contains information about the execution state of the query, including the field name, path to the field from the root, and more. It’s only documented in [the GraphQL.js source code](https://github.com/graphql/graphql-js/blob/c82ff68f52722c20f10da69c9e50a030a1f218ae/src/type/definition.js#L489-L500).
107+
108+
## Examples of directives
109+
110+
### Text formatting: `@upperCase`
111+
112+
Text formatting is a good use case for directives. It can be helpful to directly format your text in your queries or to ensure that a field has a specific format server-side.
113+
114+
```js
115+
import { buildSchema } from 'graphql'
116+
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directives'
117+
118+
// Schema
119+
const schema = buildSchema(`
120+
directive @upperCase on FIELD_DEFINITION | FIELD
121+
`)
122+
123+
// Resolver
124+
addDirectiveResolveFunctionsToSchema(schema, {
125+
async dateFormat(resolve, source, args) {
126+
const value = await resolve()
127+
return format(new Date(value), args.format)
128+
},
129+
})
130+
```
131+
132+
[See complete example](https://github.com/smooth-code/graphql-directives/blob/master/examples/upperCase.js)
133+
134+
### Date formatting: `@dateFormat(format: String)`
135+
136+
Date formatting is a CPU expensive operation. Since all directives are resolved server-side, it speeds up your client and it is easily cachable.
137+
138+
```js
139+
import { buildSchema } from 'graphql'
140+
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directives'
141+
import format from 'date-fns/format'
142+
143+
// Schema
144+
const schema = buildSchema(`
145+
directive @dateFormat(format: String) on FIELD_DEFINITION | FIELD
146+
`)
147+
148+
// Resolver
149+
addDirectiveResolveFunctionsToSchema(schema, {
150+
async dateFormat(resolve, source, args) {
151+
const value = await resolve()
152+
return format(new Date(value), args.format)
153+
},
154+
})
155+
```
156+
157+
[See complete example](https://github.com/smooth-code/graphql-directives/blob/master/examples/dateFormat.js)
158+
159+
### Authentication: `@requireAuth`
160+
161+
Authentication is a very good usage of `FIELD_DEFINITION` directives. By using a directive you can restrict only one specific field without modifying your resolvers.
162+
163+
```js
164+
import { buildSchema } from 'graphql'
165+
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directives'
166+
167+
// Schema
168+
const schema = buildSchema(`
169+
directive @requireAuth on FIELD_DEFINITION
170+
`)
171+
172+
// Resolver
173+
addDirectiveResolveFunctionsToSchema(schema, {
174+
requireAuth(resolve, directiveArgs, obj, context, info) {
175+
if (!context.isAuthenticated)
176+
throw new Error(`You must be authenticated to access "${info.fieldName}"`)
177+
return resolve()
178+
},
179+
})
180+
```
181+
182+
[See complete example](https://github.com/smooth-code/graphql-directives/blob/master/examples/requireAuth.js)
183+
184+
## Limitations
185+
186+
* `FIELD` and `FIELD_DEFINITION` are the only two supported locations
187+
* [Apollo InMemoryCache](https://www.apollographql.com/docs/react/basics/caching.html) doesn't support custom directives yet. **Be careful: using custom directives in your queries can corrupt your cache.**
188+
189+
## Inspiration
190+
191+
* https://github.com/apollographql/graphql-tools/pull/518
192+
* [graphql-custom-directive](https://github.com/lirown/graphql-custom-directive)
193+
194+
## License
195+
196+
MIT
197+
198+
[build-badge]: https://img.shields.io/travis/smooth-code/graphql-directives.svg?style=flat-square
199+
[build]: https://travis-ci.org/smooth-code/graphql-directives
200+
[coverage-badge]: https://img.shields.io/codecov/c/github/smooth-code/graphql-directives.svg?style=flat-square
201+
[coverage]: https://codecov.io/github/smooth-code/graphql-directives
202+
[version-badge]: https://img.shields.io/npm/v/graphql-directives.svg?style=flat-square
203+
[package]: https://www.npmjs.com/package/graphql-directives
204+
[license-badge]: https://img.shields.io/npm/l/graphql-directives.svg?style=flat-square
205+
[license]: https://github.com/smooth-code/graphql-directives/blob/master/LICENSE

examples/dateFormat.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/* eslint-disable import/no-extraneous-dependencies, no-console */
2+
import { buildSchema, graphql } from 'graphql'
3+
import format from 'date-fns/format'
4+
import { addDirectiveResolveFunctionsToSchema } from '../src'
5+
6+
// Create schema with directive declarations
7+
const schema = buildSchema(/* GraphQL */ `
8+
# Format date using "date-fns/format"
9+
directive @dateFormat(format: String) on FIELD_DEFINITION | FIELD
10+
11+
type Book {
12+
title: String
13+
publishedDate: String @dateFormat(format: "DD-MM-YYYY")
14+
}
15+
16+
type Query {
17+
book: Book
18+
}
19+
`)
20+
21+
// Add directive resolvers to schema
22+
addDirectiveResolveFunctionsToSchema(schema, {
23+
async dateFormat(resolve, source, directiveArgs) {
24+
const value = await resolve()
25+
return format(new Date(value), directiveArgs.format)
26+
},
27+
})
28+
29+
// Use directive in query
30+
const query = /* GraphQL */ `
31+
{
32+
book {
33+
title
34+
publishedDate
35+
publishedYear: publishedDate @dateFormat(format: "YYYY")
36+
}
37+
}
38+
`
39+
40+
const rootValue = {
41+
book: () => ({
42+
title: 'Harry Potter',
43+
publishedDate: '1997-06-12T00:00:00.000Z',
44+
}),
45+
}
46+
47+
graphql(schema, query, rootValue).then(response => {
48+
console.log(response.data)
49+
// { book:
50+
// { title: 'Harry Potter',
51+
// publishedDate: '12-06-1997',
52+
// publishedYear: '1997' } }
53+
})

0 commit comments

Comments
 (0)