Nextjs、authLink、httpLink和GraphQL订阅问题

moiiocjp  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(121)

有一些问题,让这个发挥球。经过一些挖掘,我发现nextjs/ssr有问题的订阅,你需要首先检查process.browser存在。但是,我现在有问题,让我的authLink与httpLink和splitLink工作。
目前我有它的设置如下,它的工作很好,但authlink是不被使用。

import {ApolloClient, ApolloLink, createHttpLink, InMemoryCache, split} from "@apollo/client"
import {setContext} from "@apollo/client/link/context"
import { WebSocketLink } from "@apollo/client/link/ws"
import {getMainDefinition} from "@apollo/client/utilities";

const httpLink = createHttpLink({
    uri: "http://localhost:4000/graphql",
})

const wsLink = process.browser ? new WebSocketLink({
    uri: 'ws://localhost:4000/graphql',
    options: {
        reconnect: true
    }
}) : null

const authLink = setContext((_, { headers }) => {
    const token = localStorage.getItem('token')

    return {
        headers: {
            ...headers,
            authorization: token
        }
    }
})

const splitLink = process.browser ? split(({ query }) => {
    const definition = getMainDefinition(query)
    return (
        definition.kind === 'OperationDefinition' && definition.operation === 'subscription'
    )
}, wsLink, httpLink) : httpLink

const client = new ApolloClient({
    link: splitLink,
    cache: new InMemoryCache(),
});

export default client;

我现在还想包括authLink,并尝试使用concat或ApolloLink创建链接,例如:

const client = new ApolloClient({
    link: ApolloLink.from([splitLink, authLink]),
    cache: new InMemoryCache(),
});

但我得到的错误:

Error: You are calling concat on a terminating link, which will have no effect

有什么建议我还可以在这里尝试吗?
谢谢

vmdwslir

vmdwslir1#

交换链接的顺序,如下所示:

const client = new ApolloClient({
    link: ApolloLink.from([authLink, splitLink]),
    cache: new InMemoryCache(),
});

参考:www.example.comhttps://www.apollographql.com/docs/react/api/link/introduction/#the-terminating-link

相关问题