4

你能帮忙检查一下我的代码,我是否可以从 cookie 中获取访问令牌并通过 apollo 客户端发送它?在我的 Next.js 项目中,我使用 NextAuth 进行身份验证。用户登录后,我在会话中保存用户信息和访问令牌。但我知道我怎样才能得到它并通过 apollo 客户端传递它。

import { useMemo } from 'react'
import { ApolloClient, ApolloLink, InMemoryCache, createHttpLink } from '@apollo/client'
import { setContext } from '@apollo/client/link/context';
import { concatPagination } from '@apollo/client/utilities'
import merge from 'deepmerge'
import isEqual from 'lodash/isEqual'

export const APOLLO_STATE_PROP_NAME = '__APOLLO_STATE__'

let apolloClient

const CLIENT_URL =
  process.env.NODE_ENV === 'production'
    ? process.env.API_END_POINT
    : 'http://localhost:1337'

function createApolloClient() {
  const httpLink = createHttpLink({
    uri: `${CLIENT_URL}/graphql`,
    credentials: 'same-origin'
  });

  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : ''
      }
    }
  });

  const cache = new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          jobs: concatPagination(),
        },
      },
    },
  });

  const client = new ApolloClient({
    srMode: typeof window === 'undefined',
    link: authLink.concat(httpLink),
    cache
  });

  return client;

}

export function initializeApollo(initialState = null) {
  const _apolloClient = apolloClient ?? createApolloClient()

  // If your page has Next.js data fetching methods that use Apollo Client, the initial state
  // gets hydrated here
  if (initialState) {
    // Get existing cache, loaded during client side data fetching
    const existingCache = _apolloClient.extract()

    // Merge the existing cache into data passed from getStaticProps/getServerSideProps
    const data = merge(initialState, existingCache, {
      // combine arrays using object equality (like in sets)
      arrayMerge: (destinationArray, sourceArray) => [
        ...sourceArray,
        ...destinationArray.filter((d) =>
          sourceArray.every((s) => !isEqual(d, s))
        ),
      ],
    })

    // Restore the cache with the merged data
    _apolloClient.cache.restore(data)
  }
  // For SSG and SSR always create a new Apollo Client
  if (typeof window === 'undefined') return _apolloClient
  // Create the Apollo Client once in the client
  if (!apolloClient) apolloClient = _apolloClient

  return _apolloClient
}

export function addApolloState(client, pageProps) {
  if (pageProps?.props) {
    pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract()
  }

  return pageProps
}

export function useApollo(pageProps) {
  const state = pageProps[APOLLO_STATE_PROP_NAME]
  const store = useMemo(() => initializeApollo(state), [state])
  return store
}
4

0 回答 0