npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

graphql-directive

v0.2.1

Published

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

Downloads

55

Readme

graphql-directive

Build Status Code Coverage version MIT License

GraphQL supports several 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.

Install

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:

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.

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.

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.

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

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.

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

// Schema
const schema = buildSchema(`
  directive @upperCase 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

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.

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

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.

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

Limitations

Inspiration

License

MIT