master 46024c330cae cached
18 files
32.4 KB
8.4k tokens
24 symbols
1 requests
Download .txt
Repository: smooth-code/graphql-directive
Branch: master
Commit: 46024c330cae
Files: 18
Total size: 32.4 KB

Directory structure:
gitextract_9q_c_7bx/

├── .babelrc
├── .eslintignore
├── .eslintrc.js
├── .gitignore
├── .npmignore
├── .prettierrc
├── .travis.yml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── examples/
│   ├── dateFormat.js
│   ├── requireAuth.js
│   └── upperCase.js
├── package.json
├── scripts/
│   └── ci.sh
└── src/
    ├── addDirectiveResolveFunctionsToSchema.js
    ├── addDirectiveResolveFunctionsToSchema.test.js
    └── index.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .babelrc
================================================
{
  "presets": [
    ["env", {
      "targets": {
        "node": "6"
      }
    }]
  ],
  "plugins": [
    "transform-class-properties",
    "transform-object-rest-spread"
  ]
}


================================================
FILE: .eslintignore
================================================
node_modules/
lib/


================================================
FILE: .eslintrc.js
================================================
module.exports = {
  root: true,
  extends: ['airbnb-base', 'prettier'],
  parser: 'babel-eslint',
  parserOptions: {
    ecmaVersion: 8,
    sourceType: 'module',
  },
  env: {
    jest: true,
  },
  rules: {
    'class-methods-use-this': 'off',
    'no-param-reassign': 'off',
    'no-use-before-define': 'off',
    'import/prefer-default-export': 'off',
  },
}



================================================
FILE: .gitignore
================================================
node_modules/
coverage/
lib/


================================================
FILE: .npmignore
================================================
/*
!/lib/*.js
*.test.js


================================================
FILE: .prettierrc
================================================
{
  "singleQuote": true,
  "trailingComma": "all",
  "semi": false
}


================================================
FILE: .travis.yml
================================================
language: node_js

node_js:
  - 6
  - 8

before_install:
  - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.3.2
  - export PATH="$HOME/.yarn/bin:$PATH"

script:
  - yarn ci

notifications:
  email: false

cache:
  yarn: true
  directories:
    - "node_modules"


================================================
FILE: CHANGELOG.md
================================================
# Change Log

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.

<a name="0.2.1"></a>
## [0.2.1](https://github.com/smooth-code/graphql-directive/compare/v0.2.0...v0.2.1) (2018-02-22)


### Bug Fixes

* 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)



<a name="0.2.0"></a>
# [0.2.0](https://github.com/smooth-code/graphql-directive/compare/v0.1.1...v0.2.0) (2018-01-09)


### Features

* 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)



<a name="0.1.1"></a>
## [0.1.1](https://github.com/smooth-code/graphql-directive/compare/v0.1.0...v0.1.1) (2017-12-13)


### Bug Fixes

* do not throw error if resolver is a built-in one ([0b768c2](https://github.com/smooth-code/graphql-directive/commit/0b768c2))



<a name="0.1.0"></a>
# 0.1.0 (2017-12-10)


### Features

* add support for FIELD and FIELD_DEFINITION directives ([3d1f0e9](https://github.com/smooth-code/graphql-directive/commit/3d1f0e9))


================================================
FILE: LICENSE
================================================
Copyright 2017 Smooth Code

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.


================================================
FILE: README.md
================================================
# graphql-directive

[![Build Status][build-badge]][build]
[![Code Coverage][coverage-badge]][coverage]
[![version][version-badge]][package]
[![MIT License][license-badge]][license]

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.

Custom directives have a lot of use-cases:

* Formatting
* Authentication
* Introspection
* ...

You can [learn more about directives in GraphQL documentation](http://graphql.org/learn/queries/#directives).

## Install

```sh
npm install graphql-directive
```

## Steps

### 1. Define a directive in schema

A directive must be defined in your schema, it can be done using the keyword `directive`:

```graphql
directive @dateFormat(format: String) on FIELD | FIELD_DEFINITION
```

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).

**FIELD AND FIELD_DEFINITION are the only two directive locations supported.**

### 2. Add directive resolver

The second step consists in adding a resolver for the custom directive.

```js
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directive'

// Attach a resolver map to schema
addDirectiveResolveFunctionsToSchema(schema, {
  async dateFormat(resolve, source, args) {
    const value = await resolve()
    return format(new Date(value), args.format)
  },
})
```

### 3. Use directive in query

You can now use your directive either in schema or in query.

```js
import { graphql } from 'graphql'

const QUERY = `{ publishDate @dateFormat(format: "DD-MM-YYYY") }`

const rootValue = { publishDate: '1997-06-12T00:00:00.000Z' }

graphql(schema, query, rootValue).then(response => {
  console.log(response.data) // { publishDate: '12-06-1997' }
})
```

## Usage

### addDirectiveResolveFunctionsToSchema(schema, resolverMap)

`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.

```js
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directive'

const resolverMap = {
  // Will be called when a @upperCase directive is applied to a field.
  async upperCase(resolve) {
    const value = await resolve()
    return value.toString().toUpperCase()
  },
}

// Attach directive resolvers to schema.
addDirectiveResolveFunctionsToSchema(schema, resolverMap)
```

### Directive resolver function signature

Every directive resolver accepts five positional arguments:

```
directiveName(resolve, obj, directiveArgs, context, info) { result }
```

These arguments have the following conventional names and meanings:

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.
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.
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" }`.
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.
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).

## Examples of directives

### Text formatting: `@upperCase`

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.

```js
import { buildSchema } from 'graphql'
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directive'

// Schema
const schema = buildSchema(`
  directive @upperCase on FIELD_DEFINITION | FIELD
`)

// Resolver
addDirectiveResolveFunctionsToSchema(schema, {
  async upperCase(resolve) {
    const value = await resolve()
    return value.toUpperCase()
  },
})
```

[See complete example](https://github.com/smooth-code/graphql-directive/blob/master/examples/upperCase.js)

### Date formatting: `@dateFormat(format: String)`

Date formatting is a CPU expensive operation. Since all directives are resolved server-side, it speeds up your client and it is easily cachable.

```js
import { buildSchema } from 'graphql'
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directive'
import format from 'date-fns/format'

// Schema
const schema = buildSchema(`
  directive @dateFormat(format: String) on FIELD_DEFINITION | FIELD
`)

// Resolver
addDirectiveResolveFunctionsToSchema(schema, {
  async dateFormat(resolve, source, args) {
    const value = await resolve()
    return format(new Date(value), args.format)
  },
})
```

[See complete example](https://github.com/smooth-code/graphql-directive/blob/master/examples/dateFormat.js)

### Authentication: `@requireAuth`

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.

```js
import { buildSchema } from 'graphql'
import { addDirectiveResolveFunctionsToSchema } from 'graphql-directive'

// Schema
const schema = buildSchema(`
  directive @requireAuth on FIELD_DEFINITION
`)

// Resolver
addDirectiveResolveFunctionsToSchema(schema, {
  requireAuth(resolve, directiveArgs, obj, context, info) {
    if (!context.isAuthenticated)
      throw new Error(`You must be authenticated to access "${info.fieldName}"`)
    return resolve()
  },
})
```

[See complete example](https://github.com/smooth-code/graphql-directive/blob/master/examples/requireAuth.js)

## Limitations

* `FIELD` and `FIELD_DEFINITION` are the only two supported locations
* [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).

## Inspiration

* https://github.com/apollographql/graphql-tools/pull/518
* [graphql-custom-directive](https://github.com/lirown/graphql-custom-directive)

## License

MIT

[build-badge]: https://img.shields.io/travis/smooth-code/graphql-directive.svg?style=flat-square
[build]: https://travis-ci.org/smooth-code/graphql-directive
[coverage-badge]: https://img.shields.io/codecov/c/github/smooth-code/graphql-directive.svg?style=flat-square
[coverage]: https://codecov.io/github/smooth-code/graphql-directive
[version-badge]: https://img.shields.io/npm/v/graphql-directive.svg?style=flat-square
[package]: https://www.npmjs.com/package/graphql-directive
[license-badge]: https://img.shields.io/npm/l/graphql-directive.svg?style=flat-square
[license]: https://github.com/smooth-code/graphql-directive/blob/master/LICENSE


================================================
FILE: examples/dateFormat.js
================================================
/* eslint-disable import/no-extraneous-dependencies, no-console */
import { buildSchema, graphql } from 'graphql'
import format from 'date-fns/format'
import { addDirectiveResolveFunctionsToSchema } from '../src'

// Create schema with directive declarations
const schema = buildSchema(/* GraphQL */ `
  # Format date using "date-fns/format"
  directive @dateFormat(format: String) on FIELD_DEFINITION | FIELD

  type Book {
    title: String
    publishedDate: String @dateFormat(format: "DD-MM-YYYY")
  }

  type Query {
    book: Book
  }
`)

// Add directive resolvers to schema
addDirectiveResolveFunctionsToSchema(schema, {
  async dateFormat(resolve, source, directiveArgs) {
    const value = await resolve()
    return format(new Date(value), directiveArgs.format)
  },
})

// Use directive in query
const query = /* GraphQL */ `
  {
    book {
      title
      publishedDate
      publishedYear: publishedDate @dateFormat(format: "YYYY")
    }
  }
`

const rootValue = {
  book: () => ({
    title: 'Harry Potter',
    publishedDate: '1997-06-12T00:00:00.000Z',
  }),
}

graphql(schema, query, rootValue).then(response => {
  console.log(response.data)
  // { book:
  //  { title: 'Harry Potter',
  //    publishedDate: '12-06-1997',
  //    publishedYear: '1997' } }
})


================================================
FILE: examples/requireAuth.js
================================================
/* eslint-disable import/no-extraneous-dependencies, no-console */
import { buildSchema, graphql } from 'graphql'
import { addDirectiveResolveFunctionsToSchema } from '../src'

// Create schema with directive declarations
const schema = buildSchema(/* GraphQL */ `
  # Require authentication on a specific field
  directive @requireAuth on FIELD_DEFINITION

  type Query {
    allowed: String
    unallowed: String @requireAuth
  }
`)

// Add directive resolvers to schema
addDirectiveResolveFunctionsToSchema(schema, {
  requireAuth(resolve, directiveArgs, obj, context, info) {
    if (!context.isAuthenticated)
      throw new Error(`You must be authenticated to access "${info.fieldName}"`)
    return resolve()
  },
})

const query = /* GraphQL */ `
  {
    allowed
    unallowed
  }
`

const rootValue = { allowed: 'allowed', unallowed: 'unallowed' }

graphql(schema, query, rootValue, { isAuthenticated: false }).then(response => {
  console.log(response.data) // { allowed: 'allowed', unallowed: null }
  console.log(response.errors) // [ { Error: You must be authenticated to access "unallowed" } ]
})


================================================
FILE: examples/upperCase.js
================================================
/* eslint-disable import/no-extraneous-dependencies, no-console */
import { buildSchema, graphql } from 'graphql'
import { addDirectiveResolveFunctionsToSchema } from '../src'

// Create schema with directive declarations
const schema = buildSchema(/* GraphQL */ `
  # Format field result into upperCase
  directive @upperCase on FIELD_DEFINITION | FIELD

  type Query {
    foo: String
  }
`)

// Add directive resolvers to schema
addDirectiveResolveFunctionsToSchema(schema, {
  async upperCase(resolve) {
    const value = await resolve()
    return String(value).toUpperCase()
  },
})

// Use directive in query
const query = /* GraphQL */ `
  {
    foo @upperCase
  }
`

const rootValue = { foo: 'foo' }

graphql(schema, query, rootValue).then(response => {
  console.log(response.data) // { foo: 'FOO' }
})


================================================
FILE: package.json
================================================
{
  "name": "graphql-directive",
  "version": "0.2.1",
  "main": "lib/index.js",
  "repository": "git@github.com:smooth-code/graphql-directive.git",
  "author": "Greg Bergé <greg@smooth-code.com>",
  "keywords": [
    "graphql",
    "graphql-custom-directives",
    "graphql-tools",
    "directive",
    "directives"
  ],
  "license": "MIT",
  "scripts": {
    "build": "rm -rf lib/ && NODE_ENV=production babel src -d lib --ignore \"*.test.js\"",
    "ci": "./scripts/ci.sh",
    "format": "prettier --write \"src/**/*.js\"",
    "lint": "eslint .",
    "prepublishOnly": "yarn build",
    "release": "yarn build && standard-version && conventional-github-releaser -p angular",
    "test": "jest"
  },
  "jest": {
    "collectCoverageFrom": [
      "**/*.js",
      "!.eslintrc.js",
      "!**/lib/**",
      "!**/examples/**",
      "!**/node_modules/**"
    ]
  },
  "peerDependencies": {
    "graphql": "^0.11.0 || ^0.12.0"
  },
  "dependencies": {
    "graphql-tools": "^2.21.0"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.2.2",
    "babel-jest": "^22.4.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "codecov": "^3.6.5",
    "conventional-github-releaser": "^2.0.0",
    "date-fns": "^1.29.0",
    "eslint": "^4.18.1",
    "eslint-config-airbnb-base": "^12.1.0",
    "eslint-config-prettier": "^2.9.0",
    "eslint-plugin-import": "^2.9.0",
    "graphql": "^0.13.1",
    "jest": "^22.4.0",
    "prettier": "^1.10.2",
    "standard-version": "^4.3.0"
  }
}


================================================
FILE: scripts/ci.sh
================================================
echo "Building"
yarn build

echo "Linting"
yarn lint

echo "Installing graphql@^0.12"
yarn add graphql@^0.12

echo "Running tests on graphql@^0.12"
yarn test

echo "Installing graphql ^0.11"
yarn add graphql@^0.11

echo "Running tests on graphql@^0.11"
yarn test --coverage && codecov


================================================
FILE: src/addDirectiveResolveFunctionsToSchema.js
================================================
import { forEachField } from 'graphql-tools'
import { defaultFieldResolver } from 'graphql'
import * as graphqlLanguage from 'graphql/language'
import * as graphqlType from 'graphql/type'
import { getDirectiveValues } from 'graphql/execution'

const DirectiveLocation =
  graphqlLanguage.DirectiveLocation || graphqlType.DirectiveLocation

const BUILT_IN_DIRECTIVES = ['deprecated', 'skip', 'include']

function getFieldResolver(field) {
  const resolver = field.resolve || defaultFieldResolver
  return resolver.bind(field)
}

function createAsyncResolver(field) {
  const originalResolver = getFieldResolver(field)
  return async (source, args, context, info) =>
    originalResolver(source, args, context, info)
}

function getDirectiveInfo(directive, resolverMap, schema, location, variables) {
  const name = directive.name.value

  const Directive = schema.getDirective(name)
  if (typeof Directive === 'undefined') {
    throw new Error(
      `Directive @${name} is undefined. ` +
      'Please define in schema before using.',
    )
  }

  if (!Directive.locations.includes(location)) {
    throw new Error(
      `Directive @${name} is not marked to be used on "${location}" location. ` +
      `Please add "directive @${name} ON ${location}" in schema.`,
    )
  }

  const resolver = resolverMap[name]
  if (!resolver) {
    throw new Error(
      `Directive @${name} has no resolver.` +
      'Please define one using createFieldExecutionResolver().',
    )
  }

  const args = getDirectiveValues(Directive, { directives: [directive] }, variables)
  return { args, resolver }
}

function filterCustomDirectives(directives) {
  return directives.filter(directive => !BUILT_IN_DIRECTIVES.includes(directive.name.value))
}

function createFieldExecutionResolver(field, resolverMap, schema) {
  const directives = filterCustomDirectives(field.astNode.directives)
  if (!directives.length) return getFieldResolver(field)
  return directives.reduce((recursiveResolver, directive) => {
    const directiveInfo = getDirectiveInfo(
      directive,
      resolverMap,
      schema,
      DirectiveLocation.FIELD_DEFINITION,
    )
    return (source, args, context, info) => directiveInfo.resolver(
      () => recursiveResolver(source, args, context, info),
      source,
      directiveInfo.args,
      context,
      info,
    )
  }, createAsyncResolver(field))
}

function createFieldResolver(field, resolverMap, schema) {
  const originalResolver = getFieldResolver(field)
  const asyncResolver = createAsyncResolver(field)
  return (source, args, context, info) => {
    const directives = filterCustomDirectives(info.fieldNodes[0].directives)
    if (!directives.length) return originalResolver(source, args, context, info)
    const fieldResolver = directives.reduce((recursiveResolver, directive) => {
      const directiveInfo = getDirectiveInfo(
        directive,
        resolverMap,
        schema,
        DirectiveLocation.FIELD,
        info.variableValues,
      )
      return () =>
        directiveInfo.resolver(
          () => recursiveResolver(source, args, context, info),
          source,
          directiveInfo.args,
          context,
          info,
        )
    }, asyncResolver)

    return fieldResolver(source, args, context, info)
  }
}

function addDirectiveResolveFunctionsToSchema(schema, resolverMap) {
  if (typeof resolverMap !== 'object') {
    throw new Error(
      `Expected resolverMap to be of type object, got ${typeof resolverMap}`,
    )
  }

  if (Array.isArray(resolverMap)) {
    throw new Error('Expected resolverMap to be of type object, got Array')
  }

  forEachField(schema, field => {
    field.resolve = createFieldExecutionResolver(field, resolverMap, schema)
    field.resolve = createFieldResolver(field, resolverMap, schema)
  })
}

export default addDirectiveResolveFunctionsToSchema


================================================
FILE: src/addDirectiveResolveFunctionsToSchema.test.js
================================================
/* eslint-disable no-shadow */
import url from 'url';
import { makeExecutableSchema } from 'graphql-tools'
import { graphql } from 'graphql'
import { addDirectiveResolveFunctionsToSchema } from './'

const run = async (schema, query, context, variables) => {
  const { data, errors } = await graphql(schema, query, null, context, variables)
  if (errors && errors.length) {
    /* eslint-disable no-console */
    console.error(errors)
    /* eslint-enable no-console */
    throw new Error('Error during GraphQL request')
  }
  return data
}

describe('addDirectiveResolveFunctionsToSchema', () => {
  describe('FIELD_DEFINITION (schema)', () => {
    let schema

    beforeEach(() => {
      const typeDefs = /* GraphQL */ `
        directive @upperCase on FIELD_DEFINITION
        directive @substr(start: Int!, end: Int!) on FIELD_DEFINITION
        directive @prefixWithId on FIELD_DEFINITION
        directive @getContextKey(key: String!) on FIELD_DEFINITION
        directive @getFieldName on FIELD_DEFINITION

        type Query {
          foo: String
          upperCaseFoo: String @upperCase
          asyncUpperCaseFoo: String @upperCase
          substrFoo: String @substr(start: 1, end: 2)
          substrUppercaseFoo: String @substr(start: 1, end: 2) @upperCase
          book: Book
          version: String @getContextKey(key: "version")
          nameOfField: String @getFieldName
        }

        type Book {
          name: String
          slug: String @prefixWithId
        }
      `

      const fooResolver = () => 'foo'

      const resolvers = {
        Query: {
          foo: fooResolver,
          upperCaseFoo: fooResolver,
          asyncUpperCaseFoo: async () => fooResolver(),
          substrFoo: fooResolver,
          substrUppercaseFoo: fooResolver,
          book() {
            return { id: 1, name: 'Harry Potter', slug: 'harry-potter' }
          },
        },
      }

      const directiveResolvers = {
        async upperCase(resolve) {
          const value = await resolve()
          return value.toUpperCase()
        },
        async substr(resolve, source, directiveArgs) {
          const value = await resolve()
          return value.substr(directiveArgs.start, directiveArgs.end)
        },
        async prefixWithId(resolve, source) {
          const value = await resolve()
          return `${source.id}-${value}`
        },
        getContextKey(resolve, source, directiveArgs, context) {
          return context[directiveArgs.key]
        },
        getFieldName(resolve, source, directiveArgs, context, info) {
          return info.fieldName
        },

      }

      schema = makeExecutableSchema({ typeDefs, resolvers })
      addDirectiveResolveFunctionsToSchema(schema, directiveResolvers)
    })

    it('should throw an error if not present in schema', () => {
      expect.assertions(1)
      const typeDefs = /* GraphQL */ `
        type Query {
          foo: String @foo
        }
      `
      const resolvers = {
        Query: {
          foo: () => 'foo',
        },
      }
      const schema = makeExecutableSchema({ typeDefs, resolvers })
      try {
        addDirectiveResolveFunctionsToSchema(schema, {})
      } catch (error) {
        expect(error.message).toBe(
          'Directive @foo is undefined. Please define in schema before using.',
        )
      }
    })

    it('should throw an error if resolverMap is not an object', () => {
      expect.assertions(1)
      try {
        addDirectiveResolveFunctionsToSchema(schema)
      } catch (error) {
        expect(error.message).toBe(
          'Expected resolverMap to be of type object, got undefined',
        )
      }
    })

    it('should throw an error if resolverMap is an array', () => {
      expect.assertions(1)
      try {
        addDirectiveResolveFunctionsToSchema(schema, [])
      } catch (error) {
        expect(error.message).toBe(
          'Expected resolverMap to be of type object, got Array',
        )
      }
    })

    it('should throw an error if FIELD_DEFINITION is missing', async () => {
      expect.assertions(1)
      const typeDefs = /* GraphQL */ `
        directive @foo on FIELD

        type Query {
          foo: String @foo
        }
      `
      const resolvers = {
        Query: {
          foo: () => 'foo',
        },
      }
      const schema = makeExecutableSchema({ typeDefs, resolvers })
      try {
        addDirectiveResolveFunctionsToSchema(schema, {})
      } catch (error) {
        expect(error.message).toBe(
          'Directive @foo is not marked to be used on "FIELD_DEFINITION" location. Please add "directive @foo ON FIELD_DEFINITION" in schema.',
        )
      }
    })

    it('should throw an error if resolver is not defined', async () => {
      expect.assertions(1)
      const typeDefs = /* GraphQL */ `
        directive @foo on FIELD_DEFINITION

        type Query {
          foo: String @foo
        }
      `
      const resolvers = {
        Query: {
          foo: () => 'foo',
        },
      }
      const schema = makeExecutableSchema({ typeDefs, resolvers })
      try {
        addDirectiveResolveFunctionsToSchema(schema, {})
      } catch (error) {
        expect(error.message).toBe(
          'Directive @foo has no resolver.Please define one using createFieldExecutionResolver().',
        )
      }
    })

    it('should not throw an error if resolver is a built-in schema directive', async () => {
      const typeDefs = /* GraphQL */ `
        type Query {
          foo: String @deprecated
        }
      `
      const resolvers = {
        Query: {
          foo: () => 'foo',
        },
      }
      const schema = makeExecutableSchema({ typeDefs, resolvers })
      addDirectiveResolveFunctionsToSchema(schema, {})

      const query = /* GraphQL */ `{ foo }`

      expect(await run(schema, query)).toEqual({ foo: 'foo' })
    })

    it('should not throw an error if resolver is a built-in query directive', async () => {
      const typeDefs = /* GraphQL */ `
        type Query {
          foo: String
        }
      `
      const resolvers = {
        Query: {
          foo: () => 'foo',
        },
      }
      const schema = makeExecutableSchema({ typeDefs, resolvers })
      addDirectiveResolveFunctionsToSchema(schema, {})

      const query = /* GraphQL */ `{
        foo @include(if: true)
      }`

      expect(await run(schema, query)).toEqual({ foo: 'foo' })
    })

    it('should work without directive', async () => {
      const query = /* GraphQL */ `{ foo }`
      const data = await run(schema, query)
      expect(data).toEqual({ foo: 'foo' })
    })

    it('should work with synchronous resolver', async () => {
      const query = /* GraphQL */ `{ upperCaseFoo } `
      const data = await run(schema, query)
      expect(data).toEqual({ upperCaseFoo: 'FOO' })
    })

    it('should work with asynchronous resolver', async () => {
      const query = /* GraphQL */ `{ asyncUpperCaseFoo }`
      const data = await run(schema, query)
      expect(data).toEqual({ asyncUpperCaseFoo: 'FOO' })
    })

    it('should accept directive arguments', async () => {
      const query = /* GraphQL */ `{ substrFoo }`

      const data = await run(schema, query)
      expect(data).toEqual({ substrFoo: 'oo' })
    })

    it('should be accept several directives', async () => {
      const query = /* GraphQL */ `{ substrUppercaseFoo }`
      const data = await run(schema, query)
      expect(data).toEqual({ substrUppercaseFoo: 'OO' })
    })

    it('should support source', async () => {
      const query = /* GraphQL */ `
        {
          book {
            name
            slug
          }
        }
      `

      const data = await run(schema, query)
      expect(data).toEqual({
        book: { name: 'Harry Potter', slug: '1-harry-potter' },
      })
    })

    it('should support context', async () => {
      const query = /* GraphQL */ `{ version }`
      const data = await run(schema, query, { version: '1.0' })
      expect(data).toEqual({ version: '1.0' })
    })

    it('should support info', async () => {
      const query = /* GraphQL */ `{ nameOfField }`
      const data = await run(schema, query)
      expect(data).toEqual({ nameOfField: 'nameOfField' })
    })
  })

  describe('FIELD (schema)', () => {
    let schema

    beforeEach(() => {
      const typeDefs = /* GraphQL */ `
        directive @upperCase on FIELD
        directive @substr(start: Int!, end: Int!) on FIELD
        directive @prefixWithId on FIELD
        directive @getContextKey(key: String!) on FIELD
        directive @getFieldName on FIELD
        directive @url(root: String!) on FIELD

        type Query {
          foo: String
          asyncFoo: String
          book: Book
        }

        type Book {
          name: String
          slug: String
        }
      `

      const fooResolver = () => 'foo'

      const resolvers = {
        Query: {
          foo: fooResolver,
          asyncFoo: async () => fooResolver(),
          book() {
            return { id: 1, name: 'Harry Potter', slug: 'harry-potter' }
          },
        },
      }

      const directiveResolvers = {
        async upperCase(resolve) {
          const value = await resolve()
          return value.toUpperCase()
        },
        async substr(resolve, source, directiveArgs) {
          const value = await resolve()
          return value.substr(directiveArgs.start, directiveArgs.end)
        },
        async prefixWithId(resolve, source) {
          const value = await resolve()
          return `${source.id}-${value}`
        },
        getContextKey(resolve, source, directiveArgs, context) {
          return context[directiveArgs.key]
        },
        getFieldName(resolve, source, directiveArgs, context, info) {
          return info.fieldName
        },
        async url(resolve, source, directiveArgs) {
          return url.resolve(directiveArgs.root, await resolve())
        },
      }

      schema = makeExecutableSchema({ typeDefs, resolvers })
      addDirectiveResolveFunctionsToSchema(schema, directiveResolvers)
    })

    it('should throw an error if resolver is not defined', async () => {
      const typeDefs = /* GraphQL */ `
        directive @foo on FIELD

        type Query {
          foo: String
        }
      `
      const resolvers = {
        Query: {
          foo: () => 'foo',
        },
      }
      const schema = makeExecutableSchema({ typeDefs, resolvers })
      const query = /* GraphQL */ `{ foo @foo } `
      addDirectiveResolveFunctionsToSchema(schema, {})
      const { errors } = await graphql(schema, query)
      expect(errors.length).toBe(1)
      expect(errors[0].message).toBe(
        'Directive @foo has no resolver.Please define one using createFieldExecutionResolver().',
      )
    })

    it('should work without directive', async () => {
      const query = /* GraphQL */ `{ foo }`
      const data = await run(schema, query)
      expect(data).toEqual({ foo: 'foo' })
    })

    it('should work with synchronous resolver', async () => {
      const query = /* GraphQL */ `{ foo @upperCase } `
      const data = await run(schema, query)
      expect(data).toEqual({ foo: 'FOO' })
    })

    it('should work with asynchronous resolver', async () => {
      const query = /* GraphQL */ `{ asyncFoo @upperCase }`
      const data = await run(schema, query)
      expect(data).toEqual({ asyncFoo: 'FOO' })
    })

    it('should accept directive arguments', async () => {
      const query = /* GraphQL */ `{ foo @substr(start: 1, end: 2) }`

      const data = await run(schema, query)
      expect(data).toEqual({ foo: 'oo' })
    })

    it('should be accept several directives', async () => {
      const query = /* GraphQL */ `{ foo @substr(start: 1, end: 2) @upperCase }`
      const data = await run(schema, query)
      expect(data).toEqual({ foo: 'OO' })
    })

    it('should support source', async () => {
      const query = /* GraphQL */ `
        {
          book {
            name
            slug @prefixWithId
          }
        }
      `

      const data = await run(schema, query)
      expect(data).toEqual({
        book: { name: 'Harry Potter', slug: '1-harry-potter' },
      })
    })

    it('should support context', async () => {
      const query = /* GraphQL */ `{ foo @getContextKey(key: "version") }`
      const data = await run(schema, query, { version: '1.0' })
      expect(data).toEqual({ foo: '1.0' })
    })

    it('should support info', async () => {
      const query = /* GraphQL */ `{ foo @getFieldName }`
      const data = await run(schema, query)
      expect(data).toEqual({ foo: 'foo' })
    })

    it('should support query variables binding', async () => {
      const query = /* GraphQL */ `query($url: String!) { foo @url(root:$url) }`
      const data = await run(schema, query, null, { url: '/root/url/' })
      expect(data).toEqual({ foo: '/root/url/foo' })
    })
  })
})


================================================
FILE: src/index.js
================================================
export {
  default as addDirectiveResolveFunctionsToSchema,
} from './addDirectiveResolveFunctionsToSchema'

Download .txt
gitextract_9q_c_7bx/

├── .babelrc
├── .eslintignore
├── .eslintrc.js
├── .gitignore
├── .npmignore
├── .prettierrc
├── .travis.yml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── examples/
│   ├── dateFormat.js
│   ├── requireAuth.js
│   └── upperCase.js
├── package.json
├── scripts/
│   └── ci.sh
└── src/
    ├── addDirectiveResolveFunctionsToSchema.js
    ├── addDirectiveResolveFunctionsToSchema.test.js
    └── index.js
Download .txt
SYMBOL INDEX (24 symbols across 5 files)

FILE: examples/dateFormat.js
  method dateFormat (line 23) | async dateFormat(resolve, source, directiveArgs) {

FILE: examples/requireAuth.js
  method requireAuth (line 18) | requireAuth(resolve, directiveArgs, obj, context, info) {

FILE: examples/upperCase.js
  method upperCase (line 17) | async upperCase(resolve) {

FILE: src/addDirectiveResolveFunctionsToSchema.js
  constant BUILT_IN_DIRECTIVES (line 10) | const BUILT_IN_DIRECTIVES = ['deprecated', 'skip', 'include']
  function getFieldResolver (line 12) | function getFieldResolver(field) {
  function createAsyncResolver (line 17) | function createAsyncResolver(field) {
  function getDirectiveInfo (line 23) | function getDirectiveInfo(directive, resolverMap, schema, location, vari...
  function filterCustomDirectives (line 53) | function filterCustomDirectives(directives) {
  function createFieldExecutionResolver (line 57) | function createFieldExecutionResolver(field, resolverMap, schema) {
  function createFieldResolver (line 77) | function createFieldResolver(field, resolverMap, schema) {
  function addDirectiveResolveFunctionsToSchema (line 105) | function addDirectiveResolveFunctionsToSchema(schema, resolverMap) {

FILE: src/addDirectiveResolveFunctionsToSchema.test.js
  method book (line 56) | book() {
  method upperCase (line 63) | async upperCase(resolve) {
  method substr (line 67) | async substr(resolve, source, directiveArgs) {
  method prefixWithId (line 71) | async prefixWithId(resolve, source) {
  method getContextKey (line 75) | getContextKey(resolve, source, directiveArgs, context) {
  method getFieldName (line 78) | getFieldName(resolve, source, directiveArgs, context, info) {
  method book (line 310) | book() {
  method upperCase (line 317) | async upperCase(resolve) {
  method substr (line 321) | async substr(resolve, source, directiveArgs) {
  method prefixWithId (line 325) | async prefixWithId(resolve, source) {
  method getContextKey (line 329) | getContextKey(resolve, source, directiveArgs, context) {
  method getFieldName (line 332) | getFieldName(resolve, source, directiveArgs, context, info) {
  method url (line 335) | async url(resolve, source, directiveArgs) {
Condensed preview — 18 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (35K chars).
[
  {
    "path": ".babelrc",
    "chars": 180,
    "preview": "{\n  \"presets\": [\n    [\"env\", {\n      \"targets\": {\n        \"node\": \"6\"\n      }\n    }]\n  ],\n  \"plugins\": [\n    \"transform-"
  },
  {
    "path": ".eslintignore",
    "chars": 19,
    "preview": "node_modules/\nlib/\n"
  },
  {
    "path": ".eslintrc.js",
    "chars": 365,
    "preview": "module.exports = {\n  root: true,\n  extends: ['airbnb-base', 'prettier'],\n  parser: 'babel-eslint',\n  parserOptions: {\n  "
  },
  {
    "path": ".gitignore",
    "chars": 29,
    "preview": "node_modules/\ncoverage/\nlib/\n"
  },
  {
    "path": ".npmignore",
    "chars": 24,
    "preview": "/*\n!/lib/*.js\n*.test.js\n"
  },
  {
    "path": ".prettierrc",
    "chars": 69,
    "preview": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\",\n  \"semi\": false\n}\n"
  },
  {
    "path": ".travis.yml",
    "chars": 282,
    "preview": "language: node_js\n\nnode_js:\n  - 6\n  - 8\n\nbefore_install:\n  - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --v"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 1353,
    "preview": "# Change Log\n\nAll notable changes to this project will be documented in this file. See [standard-version](https://github"
  },
  {
    "path": "LICENSE",
    "chars": 1051,
    "preview": "Copyright 2017 Smooth Code\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this softwar"
  },
  {
    "path": "README.md",
    "chars": 7737,
    "preview": "# graphql-directive\n\n[![Build Status][build-badge]][build]\n[![Code Coverage][coverage-badge]][coverage]\n[![version][vers"
  },
  {
    "path": "examples/dateFormat.js",
    "chars": 1282,
    "preview": "/* eslint-disable import/no-extraneous-dependencies, no-console */\nimport { buildSchema, graphql } from 'graphql'\nimport"
  },
  {
    "path": "examples/requireAuth.js",
    "chars": 1111,
    "preview": "/* eslint-disable import/no-extraneous-dependencies, no-console */\nimport { buildSchema, graphql } from 'graphql'\nimport"
  },
  {
    "path": "examples/upperCase.js",
    "chars": 813,
    "preview": "/* eslint-disable import/no-extraneous-dependencies, no-console */\nimport { buildSchema, graphql } from 'graphql'\nimport"
  },
  {
    "path": "package.json",
    "chars": 1640,
    "preview": "{\n  \"name\": \"graphql-directive\",\n  \"version\": \"0.2.1\",\n  \"main\": \"lib/index.js\",\n  \"repository\": \"git@github.com:smooth-"
  },
  {
    "path": "scripts/ci.sh",
    "chars": 285,
    "preview": "echo \"Building\"\nyarn build\n\necho \"Linting\"\nyarn lint\n\necho \"Installing graphql@^0.12\"\nyarn add graphql@^0.12\n\necho \"Runn"
  },
  {
    "path": "src/addDirectiveResolveFunctionsToSchema.js",
    "chars": 3854,
    "preview": "import { forEachField } from 'graphql-tools'\nimport { defaultFieldResolver } from 'graphql'\nimport * as graphqlLanguage "
  },
  {
    "path": "src/addDirectiveResolveFunctionsToSchema.test.js",
    "chars": 12983,
    "preview": "/* eslint-disable no-shadow */\nimport url from 'url';\nimport { makeExecutableSchema } from 'graphql-tools'\nimport { grap"
  },
  {
    "path": "src/index.js",
    "chars": 109,
    "preview": "export {\n  default as addDirectiveResolveFunctionsToSchema,\n} from './addDirectiveResolveFunctionsToSchema'\n\n"
  }
]

About this extraction

This page contains the full source code of the smooth-code/graphql-directive GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 18 files (32.4 KB), approximately 8.4k tokens, and a symbol index with 24 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!