├── .eslintignore ├── .npmignore ├── .gitignore ├── .prettierrc ├── src ├── index.js ├── addDirectiveResolveFunctionsToSchema.js └── addDirectiveResolveFunctionsToSchema.test.js ├── .babelrc ├── scripts └── ci.sh ├── .travis.yml ├── .eslintrc.js ├── examples ├── upperCase.js ├── requireAuth.js └── dateFormat.js ├── LICENSE ├── CHANGELOG.md ├── package.json └── README.md /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | lib/ 3 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | /* 2 | !/lib/*.js 3 | *.test.js 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | lib/ 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "semi": false 5 | } 6 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | export { 2 | default as addDirectiveResolveFunctionsToSchema, 3 | } from './addDirectiveResolveFunctionsToSchema' 4 | 5 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 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 | } 14 | -------------------------------------------------------------------------------- /scripts/ci.sh: -------------------------------------------------------------------------------- 1 | echo "Building" 2 | yarn build 3 | 4 | echo "Linting" 5 | yarn lint 6 | 7 | echo "Installing graphql@^0.12" 8 | yarn add graphql@^0.12 9 | 10 | echo "Running tests on graphql@^0.12" 11 | yarn test 12 | 13 | echo "Installing graphql ^0.11" 14 | yarn add graphql@^0.11 15 | 16 | echo "Running tests on graphql@^0.11" 17 | yarn test --coverage && codecov 18 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 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" 21 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 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 | 20 | -------------------------------------------------------------------------------- /examples/upperCase.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-extraneous-dependencies, no-console */ 2 | import { buildSchema, graphql } from 'graphql' 3 | import { addDirectiveResolveFunctionsToSchema } from '../src' 4 | 5 | // Create schema with directive declarations 6 | const schema = buildSchema(/* GraphQL */ ` 7 | # Format field result into upperCase 8 | directive @upperCase on FIELD_DEFINITION | FIELD 9 | 10 | type Query { 11 | foo: String 12 | } 13 | `) 14 | 15 | // Add directive resolvers to schema 16 | addDirectiveResolveFunctionsToSchema(schema, { 17 | async upperCase(resolve) { 18 | const value = await resolve() 19 | return String(value).toUpperCase() 20 | }, 21 | }) 22 | 23 | // Use directive in query 24 | const query = /* GraphQL */ ` 25 | { 26 | foo @upperCase 27 | } 28 | ` 29 | 30 | const rootValue = { foo: 'foo' } 31 | 32 | graphql(schema, query, rootValue).then(response => { 33 | console.log(response.data) // { foo: 'FOO' } 34 | }) 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. 8 | -------------------------------------------------------------------------------- /examples/requireAuth.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-extraneous-dependencies, no-console */ 2 | import { buildSchema, graphql } from 'graphql' 3 | import { addDirectiveResolveFunctionsToSchema } from '../src' 4 | 5 | // Create schema with directive declarations 6 | const schema = buildSchema(/* GraphQL */ ` 7 | # Require authentication on a specific field 8 | directive @requireAuth on FIELD_DEFINITION 9 | 10 | type Query { 11 | allowed: String 12 | unallowed: String @requireAuth 13 | } 14 | `) 15 | 16 | // Add directive resolvers to schema 17 | addDirectiveResolveFunctionsToSchema(schema, { 18 | requireAuth(resolve, directiveArgs, obj, context, info) { 19 | if (!context.isAuthenticated) 20 | throw new Error(`You must be authenticated to access "${info.fieldName}"`) 21 | return resolve() 22 | }, 23 | }) 24 | 25 | const query = /* GraphQL */ ` 26 | { 27 | allowed 28 | unallowed 29 | } 30 | ` 31 | 32 | const rootValue = { allowed: 'allowed', unallowed: 'unallowed' } 33 | 34 | graphql(schema, query, rootValue, { isAuthenticated: false }).then(response => { 35 | console.log(response.data) // { allowed: 'allowed', unallowed: null } 36 | console.log(response.errors) // [ { Error: You must be authenticated to access "unallowed" } ] 37 | }) 38 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | 6 | ## [0.2.1](https://github.com/smooth-code/graphql-directive/compare/v0.2.0...v0.2.1) (2018-02-22) 7 | 8 | 9 | ### Bug Fixes 10 | 11 | * support query variable binding ([#6](https://github.com/smooth-code/graphql-directive/issues/6)) ([fead242](https://github.com/smooth-code/graphql-directive/commit/fead242)), closes [#5](https://github.com/smooth-code/graphql-directive/issues/5) 12 | 13 | 14 | 15 | 16 | # [0.2.0](https://github.com/smooth-code/graphql-directive/compare/v0.1.1...v0.2.0) (2018-01-09) 17 | 18 | 19 | ### Features 20 | 21 | * add support for graphql v0.12 ([285e59d](https://github.com/smooth-code/graphql-directive/commit/285e59d)), closes [#2](https://github.com/smooth-code/graphql-directive/issues/2) 22 | 23 | 24 | 25 | 26 | ## [0.1.1](https://github.com/smooth-code/graphql-directive/compare/v0.1.0...v0.1.1) (2017-12-13) 27 | 28 | 29 | ### Bug Fixes 30 | 31 | * do not throw error if resolver is a built-in one ([0b768c2](https://github.com/smooth-code/graphql-directive/commit/0b768c2)) 32 | 33 | 34 | 35 | 36 | # 0.1.0 (2017-12-10) 37 | 38 | 39 | ### Features 40 | 41 | * add support for FIELD and FIELD_DEFINITION directives ([3d1f0e9](https://github.com/smooth-code/graphql-directive/commit/3d1f0e9)) 42 | -------------------------------------------------------------------------------- /examples/dateFormat.js: -------------------------------------------------------------------------------- 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 | }) 54 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "graphql-directive", 3 | "version": "0.2.1", 4 | "main": "lib/index.js", 5 | "repository": "git@github.com:smooth-code/graphql-directive.git", 6 | "author": "Greg Bergé ", 7 | "keywords": [ 8 | "graphql", 9 | "graphql-custom-directives", 10 | "graphql-tools", 11 | "directive", 12 | "directives" 13 | ], 14 | "license": "MIT", 15 | "scripts": { 16 | "build": "rm -rf lib/ && NODE_ENV=production babel src -d lib --ignore \"*.test.js\"", 17 | "ci": "./scripts/ci.sh", 18 | "format": "prettier --write \"src/**/*.js\"", 19 | "lint": "eslint .", 20 | "prepublishOnly": "yarn build", 21 | "release": "yarn build && standard-version && conventional-github-releaser -p angular", 22 | "test": "jest" 23 | }, 24 | "jest": { 25 | "collectCoverageFrom": [ 26 | "**/*.js", 27 | "!.eslintrc.js", 28 | "!**/lib/**", 29 | "!**/examples/**", 30 | "!**/node_modules/**" 31 | ] 32 | }, 33 | "peerDependencies": { 34 | "graphql": "^0.11.0 || ^0.12.0" 35 | }, 36 | "dependencies": { 37 | "graphql-tools": "^2.21.0" 38 | }, 39 | "devDependencies": { 40 | "babel-cli": "^6.26.0", 41 | "babel-core": "^6.26.0", 42 | "babel-eslint": "^8.2.2", 43 | "babel-jest": "^22.4.0", 44 | "babel-plugin-transform-class-properties": "^6.24.1", 45 | "babel-plugin-transform-object-rest-spread": "^6.26.0", 46 | "babel-preset-env": "^1.6.1", 47 | "codecov": "^3.6.5", 48 | "conventional-github-releaser": "^2.0.0", 49 | "date-fns": "^1.29.0", 50 | "eslint": "^4.18.1", 51 | "eslint-config-airbnb-base": "^12.1.0", 52 | "eslint-config-prettier": "^2.9.0", 53 | "eslint-plugin-import": "^2.9.0", 54 | "graphql": "^0.13.1", 55 | "jest": "^22.4.0", 56 | "prettier": "^1.10.2", 57 | "standard-version": "^4.3.0" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/addDirectiveResolveFunctionsToSchema.js: -------------------------------------------------------------------------------- 1 | import { forEachField } from 'graphql-tools' 2 | import { defaultFieldResolver } from 'graphql' 3 | import * as graphqlLanguage from 'graphql/language' 4 | import * as graphqlType from 'graphql/type' 5 | import { getDirectiveValues } from 'graphql/execution' 6 | 7 | const DirectiveLocation = 8 | graphqlLanguage.DirectiveLocation || graphqlType.DirectiveLocation 9 | 10 | const BUILT_IN_DIRECTIVES = ['deprecated', 'skip', 'include'] 11 | 12 | function getFieldResolver(field) { 13 | const resolver = field.resolve || defaultFieldResolver 14 | return resolver.bind(field) 15 | } 16 | 17 | function createAsyncResolver(field) { 18 | const originalResolver = getFieldResolver(field) 19 | return async (source, args, context, info) => 20 | originalResolver(source, args, context, info) 21 | } 22 | 23 | function getDirectiveInfo(directive, resolverMap, schema, location, variables) { 24 | const name = directive.name.value 25 | 26 | const Directive = schema.getDirective(name) 27 | if (typeof Directive === 'undefined') { 28 | throw new Error( 29 | `Directive @${name} is undefined. ` + 30 | 'Please define in schema before using.', 31 | ) 32 | } 33 | 34 | if (!Directive.locations.includes(location)) { 35 | throw new Error( 36 | `Directive @${name} is not marked to be used on "${location}" location. ` + 37 | `Please add "directive @${name} ON ${location}" in schema.`, 38 | ) 39 | } 40 | 41 | const resolver = resolverMap[name] 42 | if (!resolver) { 43 | throw new Error( 44 | `Directive @${name} has no resolver.` + 45 | 'Please define one using createFieldExecutionResolver().', 46 | ) 47 | } 48 | 49 | const args = getDirectiveValues(Directive, { directives: [directive] }, variables) 50 | return { args, resolver } 51 | } 52 | 53 | function filterCustomDirectives(directives) { 54 | return directives.filter(directive => !BUILT_IN_DIRECTIVES.includes(directive.name.value)) 55 | } 56 | 57 | function createFieldExecutionResolver(field, resolverMap, schema) { 58 | const directives = filterCustomDirectives(field.astNode.directives) 59 | if (!directives.length) return getFieldResolver(field) 60 | return directives.reduce((recursiveResolver, directive) => { 61 | const directiveInfo = getDirectiveInfo( 62 | directive, 63 | resolverMap, 64 | schema, 65 | DirectiveLocation.FIELD_DEFINITION, 66 | ) 67 | return (source, args, context, info) => directiveInfo.resolver( 68 | () => recursiveResolver(source, args, context, info), 69 | source, 70 | directiveInfo.args, 71 | context, 72 | info, 73 | ) 74 | }, createAsyncResolver(field)) 75 | } 76 | 77 | function createFieldResolver(field, resolverMap, schema) { 78 | const originalResolver = getFieldResolver(field) 79 | const asyncResolver = createAsyncResolver(field) 80 | return (source, args, context, info) => { 81 | const directives = filterCustomDirectives(info.fieldNodes[0].directives) 82 | if (!directives.length) return originalResolver(source, args, context, info) 83 | const fieldResolver = directives.reduce((recursiveResolver, directive) => { 84 | const directiveInfo = getDirectiveInfo( 85 | directive, 86 | resolverMap, 87 | schema, 88 | DirectiveLocation.FIELD, 89 | info.variableValues, 90 | ) 91 | return () => 92 | directiveInfo.resolver( 93 | () => recursiveResolver(source, args, context, info), 94 | source, 95 | directiveInfo.args, 96 | context, 97 | info, 98 | ) 99 | }, asyncResolver) 100 | 101 | return fieldResolver(source, args, context, info) 102 | } 103 | } 104 | 105 | function addDirectiveResolveFunctionsToSchema(schema, resolverMap) { 106 | if (typeof resolverMap !== 'object') { 107 | throw new Error( 108 | `Expected resolverMap to be of type object, got ${typeof resolverMap}`, 109 | ) 110 | } 111 | 112 | if (Array.isArray(resolverMap)) { 113 | throw new Error('Expected resolverMap to be of type object, got Array') 114 | } 115 | 116 | forEachField(schema, field => { 117 | field.resolve = createFieldExecutionResolver(field, resolverMap, schema) 118 | field.resolve = createFieldResolver(field, resolverMap, schema) 119 | }) 120 | } 121 | 122 | export default addDirectiveResolveFunctionsToSchema 123 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # graphql-directive 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](http://facebook.github.io/graphql/October2016/#sec-Type-System.Directives): `@include`, `@skip` and `@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-directive 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-directive' 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-directive' 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-directive' 117 | 118 | // Schema 119 | const schema = buildSchema(` 120 | directive @upperCase on FIELD_DEFINITION | FIELD 121 | `) 122 | 123 | // Resolver 124 | addDirectiveResolveFunctionsToSchema(schema, { 125 | async upperCase(resolve) { 126 | const value = await resolve() 127 | return value.toUpperCase() 128 | }, 129 | }) 130 | ``` 131 | 132 | [See complete example](https://github.com/smooth-code/graphql-directive/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-directive' 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-directive/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-directive' 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-directive/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.** [A PR is waiting to be merged to fix it](https://github.com/apollographql/apollo-client/pull/2710). 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-directive.svg?style=flat-square 199 | [build]: https://travis-ci.org/smooth-code/graphql-directive 200 | [coverage-badge]: https://img.shields.io/codecov/c/github/smooth-code/graphql-directive.svg?style=flat-square 201 | [coverage]: https://codecov.io/github/smooth-code/graphql-directive 202 | [version-badge]: https://img.shields.io/npm/v/graphql-directive.svg?style=flat-square 203 | [package]: https://www.npmjs.com/package/graphql-directive 204 | [license-badge]: https://img.shields.io/npm/l/graphql-directive.svg?style=flat-square 205 | [license]: https://github.com/smooth-code/graphql-directive/blob/master/LICENSE 206 | -------------------------------------------------------------------------------- /src/addDirectiveResolveFunctionsToSchema.test.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-shadow */ 2 | import url from 'url'; 3 | import { makeExecutableSchema } from 'graphql-tools' 4 | import { graphql } from 'graphql' 5 | import { addDirectiveResolveFunctionsToSchema } from './' 6 | 7 | const run = async (schema, query, context, variables) => { 8 | const { data, errors } = await graphql(schema, query, null, context, variables) 9 | if (errors && errors.length) { 10 | /* eslint-disable no-console */ 11 | console.error(errors) 12 | /* eslint-enable no-console */ 13 | throw new Error('Error during GraphQL request') 14 | } 15 | return data 16 | } 17 | 18 | describe('addDirectiveResolveFunctionsToSchema', () => { 19 | describe('FIELD_DEFINITION (schema)', () => { 20 | let schema 21 | 22 | beforeEach(() => { 23 | const typeDefs = /* GraphQL */ ` 24 | directive @upperCase on FIELD_DEFINITION 25 | directive @substr(start: Int!, end: Int!) on FIELD_DEFINITION 26 | directive @prefixWithId on FIELD_DEFINITION 27 | directive @getContextKey(key: String!) on FIELD_DEFINITION 28 | directive @getFieldName on FIELD_DEFINITION 29 | 30 | type Query { 31 | foo: String 32 | upperCaseFoo: String @upperCase 33 | asyncUpperCaseFoo: String @upperCase 34 | substrFoo: String @substr(start: 1, end: 2) 35 | substrUppercaseFoo: String @substr(start: 1, end: 2) @upperCase 36 | book: Book 37 | version: String @getContextKey(key: "version") 38 | nameOfField: String @getFieldName 39 | } 40 | 41 | type Book { 42 | name: String 43 | slug: String @prefixWithId 44 | } 45 | ` 46 | 47 | const fooResolver = () => 'foo' 48 | 49 | const resolvers = { 50 | Query: { 51 | foo: fooResolver, 52 | upperCaseFoo: fooResolver, 53 | asyncUpperCaseFoo: async () => fooResolver(), 54 | substrFoo: fooResolver, 55 | substrUppercaseFoo: fooResolver, 56 | book() { 57 | return { id: 1, name: 'Harry Potter', slug: 'harry-potter' } 58 | }, 59 | }, 60 | } 61 | 62 | const directiveResolvers = { 63 | async upperCase(resolve) { 64 | const value = await resolve() 65 | return value.toUpperCase() 66 | }, 67 | async substr(resolve, source, directiveArgs) { 68 | const value = await resolve() 69 | return value.substr(directiveArgs.start, directiveArgs.end) 70 | }, 71 | async prefixWithId(resolve, source) { 72 | const value = await resolve() 73 | return `${source.id}-${value}` 74 | }, 75 | getContextKey(resolve, source, directiveArgs, context) { 76 | return context[directiveArgs.key] 77 | }, 78 | getFieldName(resolve, source, directiveArgs, context, info) { 79 | return info.fieldName 80 | }, 81 | 82 | } 83 | 84 | schema = makeExecutableSchema({ typeDefs, resolvers }) 85 | addDirectiveResolveFunctionsToSchema(schema, directiveResolvers) 86 | }) 87 | 88 | it('should throw an error if not present in schema', () => { 89 | expect.assertions(1) 90 | const typeDefs = /* GraphQL */ ` 91 | type Query { 92 | foo: String @foo 93 | } 94 | ` 95 | const resolvers = { 96 | Query: { 97 | foo: () => 'foo', 98 | }, 99 | } 100 | const schema = makeExecutableSchema({ typeDefs, resolvers }) 101 | try { 102 | addDirectiveResolveFunctionsToSchema(schema, {}) 103 | } catch (error) { 104 | expect(error.message).toBe( 105 | 'Directive @foo is undefined. Please define in schema before using.', 106 | ) 107 | } 108 | }) 109 | 110 | it('should throw an error if resolverMap is not an object', () => { 111 | expect.assertions(1) 112 | try { 113 | addDirectiveResolveFunctionsToSchema(schema) 114 | } catch (error) { 115 | expect(error.message).toBe( 116 | 'Expected resolverMap to be of type object, got undefined', 117 | ) 118 | } 119 | }) 120 | 121 | it('should throw an error if resolverMap is an array', () => { 122 | expect.assertions(1) 123 | try { 124 | addDirectiveResolveFunctionsToSchema(schema, []) 125 | } catch (error) { 126 | expect(error.message).toBe( 127 | 'Expected resolverMap to be of type object, got Array', 128 | ) 129 | } 130 | }) 131 | 132 | it('should throw an error if FIELD_DEFINITION is missing', async () => { 133 | expect.assertions(1) 134 | const typeDefs = /* GraphQL */ ` 135 | directive @foo on FIELD 136 | 137 | type Query { 138 | foo: String @foo 139 | } 140 | ` 141 | const resolvers = { 142 | Query: { 143 | foo: () => 'foo', 144 | }, 145 | } 146 | const schema = makeExecutableSchema({ typeDefs, resolvers }) 147 | try { 148 | addDirectiveResolveFunctionsToSchema(schema, {}) 149 | } catch (error) { 150 | expect(error.message).toBe( 151 | 'Directive @foo is not marked to be used on "FIELD_DEFINITION" location. Please add "directive @foo ON FIELD_DEFINITION" in schema.', 152 | ) 153 | } 154 | }) 155 | 156 | it('should throw an error if resolver is not defined', async () => { 157 | expect.assertions(1) 158 | const typeDefs = /* GraphQL */ ` 159 | directive @foo on FIELD_DEFINITION 160 | 161 | type Query { 162 | foo: String @foo 163 | } 164 | ` 165 | const resolvers = { 166 | Query: { 167 | foo: () => 'foo', 168 | }, 169 | } 170 | const schema = makeExecutableSchema({ typeDefs, resolvers }) 171 | try { 172 | addDirectiveResolveFunctionsToSchema(schema, {}) 173 | } catch (error) { 174 | expect(error.message).toBe( 175 | 'Directive @foo has no resolver.Please define one using createFieldExecutionResolver().', 176 | ) 177 | } 178 | }) 179 | 180 | it('should not throw an error if resolver is a built-in schema directive', async () => { 181 | const typeDefs = /* GraphQL */ ` 182 | type Query { 183 | foo: String @deprecated 184 | } 185 | ` 186 | const resolvers = { 187 | Query: { 188 | foo: () => 'foo', 189 | }, 190 | } 191 | const schema = makeExecutableSchema({ typeDefs, resolvers }) 192 | addDirectiveResolveFunctionsToSchema(schema, {}) 193 | 194 | const query = /* GraphQL */ `{ foo }` 195 | 196 | expect(await run(schema, query)).toEqual({ foo: 'foo' }) 197 | }) 198 | 199 | it('should not throw an error if resolver is a built-in query directive', async () => { 200 | const typeDefs = /* GraphQL */ ` 201 | type Query { 202 | foo: String 203 | } 204 | ` 205 | const resolvers = { 206 | Query: { 207 | foo: () => 'foo', 208 | }, 209 | } 210 | const schema = makeExecutableSchema({ typeDefs, resolvers }) 211 | addDirectiveResolveFunctionsToSchema(schema, {}) 212 | 213 | const query = /* GraphQL */ `{ 214 | foo @include(if: true) 215 | }` 216 | 217 | expect(await run(schema, query)).toEqual({ foo: 'foo' }) 218 | }) 219 | 220 | it('should work without directive', async () => { 221 | const query = /* GraphQL */ `{ foo }` 222 | const data = await run(schema, query) 223 | expect(data).toEqual({ foo: 'foo' }) 224 | }) 225 | 226 | it('should work with synchronous resolver', async () => { 227 | const query = /* GraphQL */ `{ upperCaseFoo } ` 228 | const data = await run(schema, query) 229 | expect(data).toEqual({ upperCaseFoo: 'FOO' }) 230 | }) 231 | 232 | it('should work with asynchronous resolver', async () => { 233 | const query = /* GraphQL */ `{ asyncUpperCaseFoo }` 234 | const data = await run(schema, query) 235 | expect(data).toEqual({ asyncUpperCaseFoo: 'FOO' }) 236 | }) 237 | 238 | it('should accept directive arguments', async () => { 239 | const query = /* GraphQL */ `{ substrFoo }` 240 | 241 | const data = await run(schema, query) 242 | expect(data).toEqual({ substrFoo: 'oo' }) 243 | }) 244 | 245 | it('should be accept several directives', async () => { 246 | const query = /* GraphQL */ `{ substrUppercaseFoo }` 247 | const data = await run(schema, query) 248 | expect(data).toEqual({ substrUppercaseFoo: 'OO' }) 249 | }) 250 | 251 | it('should support source', async () => { 252 | const query = /* GraphQL */ ` 253 | { 254 | book { 255 | name 256 | slug 257 | } 258 | } 259 | ` 260 | 261 | const data = await run(schema, query) 262 | expect(data).toEqual({ 263 | book: { name: 'Harry Potter', slug: '1-harry-potter' }, 264 | }) 265 | }) 266 | 267 | it('should support context', async () => { 268 | const query = /* GraphQL */ `{ version }` 269 | const data = await run(schema, query, { version: '1.0' }) 270 | expect(data).toEqual({ version: '1.0' }) 271 | }) 272 | 273 | it('should support info', async () => { 274 | const query = /* GraphQL */ `{ nameOfField }` 275 | const data = await run(schema, query) 276 | expect(data).toEqual({ nameOfField: 'nameOfField' }) 277 | }) 278 | }) 279 | 280 | describe('FIELD (schema)', () => { 281 | let schema 282 | 283 | beforeEach(() => { 284 | const typeDefs = /* GraphQL */ ` 285 | directive @upperCase on FIELD 286 | directive @substr(start: Int!, end: Int!) on FIELD 287 | directive @prefixWithId on FIELD 288 | directive @getContextKey(key: String!) on FIELD 289 | directive @getFieldName on FIELD 290 | directive @url(root: String!) on FIELD 291 | 292 | type Query { 293 | foo: String 294 | asyncFoo: String 295 | book: Book 296 | } 297 | 298 | type Book { 299 | name: String 300 | slug: String 301 | } 302 | ` 303 | 304 | const fooResolver = () => 'foo' 305 | 306 | const resolvers = { 307 | Query: { 308 | foo: fooResolver, 309 | asyncFoo: async () => fooResolver(), 310 | book() { 311 | return { id: 1, name: 'Harry Potter', slug: 'harry-potter' } 312 | }, 313 | }, 314 | } 315 | 316 | const directiveResolvers = { 317 | async upperCase(resolve) { 318 | const value = await resolve() 319 | return value.toUpperCase() 320 | }, 321 | async substr(resolve, source, directiveArgs) { 322 | const value = await resolve() 323 | return value.substr(directiveArgs.start, directiveArgs.end) 324 | }, 325 | async prefixWithId(resolve, source) { 326 | const value = await resolve() 327 | return `${source.id}-${value}` 328 | }, 329 | getContextKey(resolve, source, directiveArgs, context) { 330 | return context[directiveArgs.key] 331 | }, 332 | getFieldName(resolve, source, directiveArgs, context, info) { 333 | return info.fieldName 334 | }, 335 | async url(resolve, source, directiveArgs) { 336 | return url.resolve(directiveArgs.root, await resolve()) 337 | }, 338 | } 339 | 340 | schema = makeExecutableSchema({ typeDefs, resolvers }) 341 | addDirectiveResolveFunctionsToSchema(schema, directiveResolvers) 342 | }) 343 | 344 | it('should throw an error if resolver is not defined', async () => { 345 | const typeDefs = /* GraphQL */ ` 346 | directive @foo on FIELD 347 | 348 | type Query { 349 | foo: String 350 | } 351 | ` 352 | const resolvers = { 353 | Query: { 354 | foo: () => 'foo', 355 | }, 356 | } 357 | const schema = makeExecutableSchema({ typeDefs, resolvers }) 358 | const query = /* GraphQL */ `{ foo @foo } ` 359 | addDirectiveResolveFunctionsToSchema(schema, {}) 360 | const { errors } = await graphql(schema, query) 361 | expect(errors.length).toBe(1) 362 | expect(errors[0].message).toBe( 363 | 'Directive @foo has no resolver.Please define one using createFieldExecutionResolver().', 364 | ) 365 | }) 366 | 367 | it('should work without directive', async () => { 368 | const query = /* GraphQL */ `{ foo }` 369 | const data = await run(schema, query) 370 | expect(data).toEqual({ foo: 'foo' }) 371 | }) 372 | 373 | it('should work with synchronous resolver', async () => { 374 | const query = /* GraphQL */ `{ foo @upperCase } ` 375 | const data = await run(schema, query) 376 | expect(data).toEqual({ foo: 'FOO' }) 377 | }) 378 | 379 | it('should work with asynchronous resolver', async () => { 380 | const query = /* GraphQL */ `{ asyncFoo @upperCase }` 381 | const data = await run(schema, query) 382 | expect(data).toEqual({ asyncFoo: 'FOO' }) 383 | }) 384 | 385 | it('should accept directive arguments', async () => { 386 | const query = /* GraphQL */ `{ foo @substr(start: 1, end: 2) }` 387 | 388 | const data = await run(schema, query) 389 | expect(data).toEqual({ foo: 'oo' }) 390 | }) 391 | 392 | it('should be accept several directives', async () => { 393 | const query = /* GraphQL */ `{ foo @substr(start: 1, end: 2) @upperCase }` 394 | const data = await run(schema, query) 395 | expect(data).toEqual({ foo: 'OO' }) 396 | }) 397 | 398 | it('should support source', async () => { 399 | const query = /* GraphQL */ ` 400 | { 401 | book { 402 | name 403 | slug @prefixWithId 404 | } 405 | } 406 | ` 407 | 408 | const data = await run(schema, query) 409 | expect(data).toEqual({ 410 | book: { name: 'Harry Potter', slug: '1-harry-potter' }, 411 | }) 412 | }) 413 | 414 | it('should support context', async () => { 415 | const query = /* GraphQL */ `{ foo @getContextKey(key: "version") }` 416 | const data = await run(schema, query, { version: '1.0' }) 417 | expect(data).toEqual({ foo: '1.0' }) 418 | }) 419 | 420 | it('should support info', async () => { 421 | const query = /* GraphQL */ `{ foo @getFieldName }` 422 | const data = await run(schema, query) 423 | expect(data).toEqual({ foo: 'foo' }) 424 | }) 425 | 426 | it('should support query variables binding', async () => { 427 | const query = /* GraphQL */ `query($url: String!) { foo @url(root:$url) }` 428 | const data = await run(schema, query, null, { url: '/root/url/' }) 429 | expect(data).toEqual({ foo: '/root/url/foo' }) 430 | }) 431 | }) 432 | }) 433 | --------------------------------------------------------------------------------