如何在客户端NextJS中使用Apollo GraphQL订阅?

时间:2020-05-12 03:12:28

标签: reactjs typescript next.js apollo apollo-client

我是NextJS的新手。我有一个页面需要显示从Hasura GraphQL后端提取的实时数据。

在其他非NextJS应用程序中,我已将GraphQL订阅与Apollo客户端库一起使用。在后台,这使用websockets。

使用订阅时,我可以让GraphQL在NextJS中工作。我很确定这是在服务器端运行的:

import React from "react";
import { AppProps } from "next/app";
import withApollo from 'next-with-apollo';
import { ApolloProvider } from '@apollo/react-hooks';
import ApolloClient, { InMemoryCache } from 'apollo-boost';
import { getToken } from "../util/auth";

interface Props extends AppProps {
    apollo: any
}

const App: React.FC<Props> = ({ Component, pageProps, apollo }) => (
    <ApolloProvider client={apollo}>
        <Component {...pageProps}/>
    </ApolloProvider>
);

export default withApollo(({ initialState }) => new ApolloClient({
    uri: "https://my_hasura_instance.com/v1/graphql",
    cache: new InMemoryCache().restore(initialState || {}),
    request: (operation: any) => {
        const token = getToken();
        operation.setContext({
            headers: {
                authorization: token ? `Bearer ${token}` : ''
            }
        });
    }
}))(App);

我以这种方式使用它:

import { useQuery } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';

const myQuery = gql`
    query {
        ...
    }
`;

const MyComponent: React.FC = () => {
    const { data } = useQuery(myQuery);
    return <p>{JSON.stringify(data)}</p>
}

但是,我想这样做:

import { useSubscription } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';


const myQuery = gql`
    subscription {
        ...
    }
`;

const MyComponent: React.FC = () => {
    const { data } = useSubscription(myQuery);
    return <p>{JSON.stringify(data)}</p>
}

我尝试过的事情

我尝试在ApolloClient中拆分HttpLink和WebsocketLink元素,如下所示:

import React from "react";
import { AppProps } from "next/app";

import { ApolloProvider } from '@apollo/react-hooks';
import withApollo from 'next-with-apollo';
import { InMemoryCache } from "apollo-cache-inmemory";
import ApolloClient from "apollo-client";
import { split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';

import { getToken } from "../util/auth";

interface Props extends AppProps {
    apollo: any
}

const App: React.FC<Props> = ({ Component, pageProps, apollo }) => (
    <ApolloProvider client={apollo}>
        <Component {...pageProps}/>
    </ApolloProvider>
);

const wsLink = new WebSocketLink({
    uri: "wss://my_hasura_instance.com/v1/graphql",
    options: {
        reconnect: true,
        timeout: 10000,
        connectionParams: () => ({
            headers: {
                authorization: getToken() ? `Bearer ${getToken()}` : ""
            }
        })
    },
});

const httpLink = new HttpLink({
    uri: "https://hasura-g3uc.onrender.com/v1/graphql",
});

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

export default withApollo(({ initialState }) => new ApolloClient({
    link: link,
    cache: new InMemoryCache().restore(initialState || {}),
}))(App);

但是当我加载页面时,我得到一个Internal Server Error,并且终端中出现此错误:

Error: Unable to find native implementation, or alternative implementation for WebSocket!

在我看来,ApolloClient然后在没有WebSocket实现的服务器端生成。我该如何在客户端进行此操作?

1 个答案:

答案 0 :(得分:1)

找到解决方法以使其正常运行,请查看此答案https://github.com/apollographql/subscriptions-transport-ws/issues/333#issuecomment-359261024