4.1.0 • Published 7 months ago

@envelop/on-resolve v4.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

@envelop/on-resolve

This plugin allows you to hook into resolves of every field in the GraphQL schema.

Useful for tracing or augmenting resolvers (and their results) with custom logic.

Getting Started

yarn add @envelop/on-resolve

Usage Example

Custom field resolutions

import { execute, parse, specifiedRules, subscribe, validate } from 'graphql'
import { envelop, useEngine } from '@envelop/core'
import { useOnResolve } from '@envelop/on-resolve'
import { specialResolver } from './my-resolvers'

const getEnveloped = envelop({
  plugins: [
    useEngine({ parse, validate, specifiedRules, execute, subscribe }),
    // ... other plugins ...
    useOnResolve(async function onResolve({ context, root, args, info, replaceResolver }) {
      // replace special field's resolver
      if (info.fieldName === 'special') {
        replaceResolver(specialResolver)
      }

      // replace field's result
      if (info.fieldName === 'alwaysHello') {
        return ({ setResult }) => {
          setResult('hello')
        }
      }
    })
  ]
})

Tracing

import { execute, parse, specifiedRules, subscribe, validate } from 'graphql'
import { envelop, Plugin, useEngine } from '@envelop/core'
import { useOnResolve } from '@envelop/on-resolve'

interface FieldTracingPluginContext {
  tracerUrl: string
}

function useFieldTracing() {
  return {
    onPluginInit({ addPlugin }) {
      addPlugin(
        useOnResolve(async function onResolve({ context, root, args, info }) {
          await fetch(context.tracerUrl, {
            method: 'POST',
            headers: {
              'content-type': 'application/json'
            },
            body: JSON.stringify({
              startedResolving: {
                ...info,
                parent: root,
                args
              }
            })
          })

          return async () => {
            await fetch(context.tracerUrl, {
              method: 'POST',
              headers: {
                'content-type': 'application/json'
              },
              body: JSON.stringify({
                endedResolving: {
                  ...info,
                  parent: root,
                  args
                }
              })
            })
          }
        })
      )
    }
  }
}

const getEnveloped = envelop({
  plugins: [
    useEngine({ parse, validate, specifiedRules, execute, subscribe }),
    // ... other plugins ...
    useSpecialResolve()
  ]
})
4.1.0

7 months ago

4.0.0

7 months ago

3.0.3

8 months ago

3.0.2

8 months ago

3.0.1

9 months ago

3.0.0

12 months ago

2.0.5

1 year ago

2.0.6

1 year ago

2.0.4

1 year ago

2.0.3

2 years ago

2.0.2

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago