urql-exchange-async-headers
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

urql-exchange-async-headers

test npm (tag)

A urql exchange which adds headers from promise value.

Install

npm install --save urql-exchange-async-headers

Or if you use Yarn:

yarn add urql-exchange-async-headers

Usage

You can need to add the asyncHeaderExchange, that this package exposes to your urql Client.

import { createClient, cacheExchange, fetchExchange } from 'urql'
import { asyncHeaderExchange } from 'urql-exchange-async-headers'

const urqlClient = createClient({
  url: 'http://localhost:1234/graphql',
  exchanges: [
    cacheExchange,
    asyncHeaderExchange(() => {
      return Promise.resolve({
        foo: 'bar',
      })
    }),
    fetchExchange,
  ],
  // You can add synchronous headers along with async headers. They will be merged at runtime.
  fetchOptions: {
    headers: {
      foo: 'bar',
    },
  },
})

Examples

Add Firebase Auth header

import { getAuth } from 'firebase/auth'
import { createClient, defaultExchanges } from 'urql'
import { asyncHeaderExchange } from 'urql-exchange-async-headers'

const urqlClient = createClient({
  url: 'http://localhost:1234/graphql',
  exchanges: [
    asyncHeaderExchange(async () => {
      const currentUser = getAuth().currentUser
      if (!currentUser) {
        return {}
      }
      const firebaseToken = await currentUser.getIdToken()
      return {
        authorization: `Bearer ${firebaseToken}`,
      }
    }),
    ...defaultExchanges,
  ],
})

Add AppSync Auth header

import { Auth } from 'aws-amplify'
import { createClient, defaultExchanges } from 'urql'
import { asyncHeaderExchange } from 'urql-exchange-async-headers'

const urqlClient = createClient({
  url: 'https://xxxxxxxxxxxxxxxxxxxxxxxxxx.appsync-api.ap-northeast-1.amazonaws.com/graphql',
  exchanges: [
    asyncHeaderExchange(async () => {
      const currentSession = await Auth.currentSession()
      return {
        authorization: currentSession.getIdToken().getJwtToken(),
        'x-amz-date': new Date().toISOString(),
        'x-amz-user-agent': 'URQL',
      }
    }),
    ...defaultExchanges,
  ],
})

Readme

Keywords

none

Package Sidebar

Install

npm i urql-exchange-async-headers

Weekly Downloads

613

Version

1.0.0

License

MIT

Unpacked Size

7.77 kB

Total Files

7

Last publish

Collaborators

  • acro5piano