All Projects β†’ smooth-code β†’ Graphql Directive

smooth-code / Graphql Directive

Licence: mit
Use custom directives in your GraphQL schema and queries 🎩

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Graphql Directive

Crypto Grommet
Crypto and equities app
Stars: ✭ 39 (-72.54%)
Mutual labels:  graphql, apollo, apollo-client
React Graphql Github Apollo
πŸš€ A React + Apollo + GraphQL GitHub Client. Your opportunity to learn about these technologies in a real world application.
Stars: ✭ 1,563 (+1000.7%)
Mutual labels:  graphql, apollo, apollo-client
Apollo Invalidation Policies
An extension of the Apollo 3 cache with support for type-based invalidation policies.
Stars: ✭ 55 (-61.27%)
Mutual labels:  graphql, apollo, apollo-client
Apollo Link
πŸ”— Interface for fetching and modifying control flow of GraphQL requests
Stars: ✭ 1,434 (+909.86%)
Mutual labels:  graphql, apollo, apollo-client
React Redux Graphql Apollo Bootstrap Webpack Starter
react js + redux + graphQL + Apollo + react router + hot reload + devTools + bootstrap + webpack starter
Stars: ✭ 127 (-10.56%)
Mutual labels:  graphql, apollo, apollo-client
Link state demo
πŸš€ Demonstrate how to support multiple stores in Apollo Link State
Stars: ✭ 30 (-78.87%)
Mutual labels:  graphql, apollo, apollo-client
Blaze Apollo
Blaze integration for the Apollo Client
Stars: ✭ 56 (-60.56%)
Mutual labels:  graphql, apollo, apollo-client
Kit
ReactQL starter kit (use the CLI)
Stars: ✭ 232 (+63.38%)
Mutual labels:  graphql, apollo, apollo-client
Artemis Dev Tool
An Apollo GraphQL Query Schema Testing Tool
Stars: ✭ 66 (-53.52%)
Mutual labels:  graphql, apollo, apollo-client
Cynthesize Frontend
Frontend written in Angular 7 and deployed GraphQL for Cynthesize. Development build: https://cynthesize-develop.netlify.com
Stars: ✭ 65 (-54.23%)
Mutual labels:  graphql, apollo, apollo-client
Chatty
A WhatsApp clone with React Native and Apollo (Tutorial)
Stars: ✭ 481 (+238.73%)
Mutual labels:  graphql, apollo, apollo-client
Guide
πŸ“– The GraphQL Guide website
Stars: ✭ 104 (-26.76%)
Mutual labels:  graphql, apollo, apollo-client
Searchkit
GraphQL API & React UI components for Elasticsearch. The easiest way to build a great search experience
Stars: ✭ 4,338 (+2954.93%)
Mutual labels:  graphql, apollo, apollo-client
React Boilerplate
βš› The stable base upon which we build our React projects at Mirego.
Stars: ✭ 39 (-72.54%)
Mutual labels:  graphql, apollo, apollo-client
Apollo Cache Hermes
A cache implementation for Apollo Client, tuned for performance
Stars: ✭ 425 (+199.3%)
Mutual labels:  graphql, apollo, apollo-client
A Pop
🎢 HD Music Streaming and Sharing Web App
Stars: ✭ 55 (-61.27%)
Mutual labels:  graphql, apollo, apollo-client
Next Graphql Blog
πŸ–Š A Blog including a server and a client. Server is built with Node, Express & a customized GraphQL-yoga server. Client is built with React, Next js & Apollo client.
Stars: ✭ 152 (+7.04%)
Mutual labels:  graphql, apollo, apollo-client
Apollo Cache Redux
Redux cache for Apollo Client 2.0. This project is no longer maintained.
Stars: ✭ 179 (+26.06%)
Mutual labels:  graphql, apollo, apollo-client
Guide To Graphql
A Frontend Developer's Guide to GraphQL (Fluent Conf 2018)
Stars: ✭ 59 (-58.45%)
Mutual labels:  graphql, apollo, apollo-client
Apollo Upload Client
A terminating Apollo Link for Apollo Client that allows FileList, File, Blob or ReactNativeFile instances within query or mutation variables and sends GraphQL multipart requests.
Stars: ✭ 1,176 (+728.17%)
Mutual labels:  graphql, apollo, apollo-client

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 upperCase(resolve) {
    const value = await resolve()
    return value.toUpperCase()
  },
})

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].