vue.js - 向所有 apollo 查询添加标头

正如标题所暗示的,我正在尝试为 apollo 进行的所有查询和更改添加一个标头。我知道我能做到

context: {
  headers: {
    'Accept-Language': $this.i18n.current;
  }
}

但这仅适用于一个查询或突变。我在 vue 中使用 nuxt,我当前的 nuxt.config.js 如下

apollo: {
    clientConfigs: {
      default: '~/plugins/apollo-config.js'
    },
    defaultOptions: {
      $query: {
        fetchPolicy: 'network-only',
        context: { // does not work
          headers: {
            "Accept-Language": $this.i18n.current, // not sure if this works as it is in config
          }
        }
      }
    },
    errorHandler: '~/plugins/apollo-error-handler.js'
  },

我很确定在这种情况下我使用的上下文错误但不确定我应该怎么做。任何帮助将不胜感激。

回答1

我根本不是 GraphQL 方面的专业人士,但去年,我取得了一些效果很好的东西(使用 JWT 标头),这是我当时得到的

nuxt.config.js

apollo: {
  clientConfigs: {
    default: '@/plugins/nuxt-apollo-config.js',
  },
  defaultOptions: {
    $query: {
      loadingKey: 'loading',
      fetchPolicy: 'network-only',
    },
  },
  authenticationType: 'Bearer',
},

这是我的

nuxt-apollo-config.js 文件

import { setContext } from 'apollo-link-context'
import { from } from 'apollo-link'
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
import { createHttpLink } from '@apollo/client/core'
import schema from '../apollo/schema.json'

const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData: schema,
})

export default ({ app, $config: { baseUrlGraphql } }) => {
  const headersConfig = setContext(() => ({
    credentials: 'same-origin',
    headers: {
      Authorization: app.$cookies.get('auth._token.local'),
      'x-company-id': app.$cookies.get('company_id'),
    },
  }))

  const cache = new InMemoryCache({ fragmentMatcher, resultCaching: false })

  return {
    defaultHttpLink: false,
    link: from([
      headersConfig,
      createHttpLink({
        credentials: 'include',
        uri: baseUrlGraphql,
        fetch: (uri, options) => {
          return fetch(uri, options)
        },
      }),
    ]),
    cache,
  }
}

import { setContext } from 'apollo-link-context' 对我来说效果很好。我不确定它是否是最好的,因为现在可能有一些内置的东西,但去年这个对我有用。

相似文章

python - Python - 在多行和多列中比较 values

我是Python的新手,我有一个如下所示的数据框(请参阅原始数据table)。最终目标是协调来自2个系统(sys1与sys2,在“源”列中标记)的记录(即id、rg、prd和数量)。我如何使用1个函数...

随机推荐

最新文章