urql可以自定义headers吗?

Can custom headers be set for urql?

Github GraphQL v4 API 具有 so-called Schema Previews,您可以在其中使用新的架构功能 - 但它需要自定义 Accept header.

我以前使用过 Apollo 客户端,但我想用 Formidables urlq 试用这个新应用。有没有办法用 urql 客户端设置客户 headers?

更新

我认为这已进入代码库,只是没有记录 - https://github.com/FormidableLabs/urql/pull/96/files

查看源代码,以下 urql createClient 对我有用:

const client = createClient({
  url: 'https://api.github.com/graphql',
  fetchOptions: {
    headers: {
      Authorization: `bearer ${GITHUB_TOKEN}`,
      Accept: 'application/vnd.github.packages-preview+json',
    },
  },
})

更新

实际上有比我原来的答案更好的方法。 createClient 接受 fetchOptions 的函数。因此,如果存在令牌,它将添加到 Authorization header

const client = createClient({
  url: 'http://localhost:8000/graphql/',
  // add token to header if present
  fetchOptions: () => {
    const token = getToken()
    return token ? { headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github.packages-preview+json' }} : {}
  },
})

这是我使用的,效果不错:

const client = createClient({
  url: 'yoururl',
  fetchOptions: {
    headers: {
      'content-type': 'application/json',
      'x-hasura-admin-secret':'********'
    },
  },
});

对于异步令牌设置,您可以使用auth exchange

import { createClient, dedupExchange, cacheExchange, fetchExchange } from 'urql';
import { authExchange } from '@urql/exchange-auth';

const getAuth = async ({ authState, mutate }) => {
  if (!authState) {
    const token = await getToken();
    const refreshToken = await getRefreshToken();
    if (token && refreshToken) {
      return { token, refreshToken };
    }
    return null;
  }

  return null;
};

const addAuthToOperation = ({ authState, operation }) => {
  if (!authState || !authState.token) {
    return operation;
  }

  const fetchOptions =
    typeof operation.context.fetchOptions === 'function'
      ? operation.context.fetchOptions()
      : operation.context.fetchOptions || {};

  return makeOperation(operation.kind, operation, {
    ...operation.context,
    fetchOptions: {
      ...fetchOptions,
      headers: {
        ...fetchOptions.headers,
        Authorization: authState.token,
      },
    },
  });
};

const client = createClient({
  url: '/graphql',
  exchanges: [
    dedupExchange,
    cacheExchange,
    authExchange({
      getAuthToken,
      addAuthToOperation,
    }),
    fetchExchange,
  ],
});