为NextJS实现Apollo客户端,但无法读取未定义的属性“ WebSocket”

时间:2019-11-08 04:01:45

标签: reactjs next.js apollo-client

在观看了各种视频并阅读了文章之后,决定从普通的React切换到NextJS。我目前正在尝试实现Apollo Client,但遇到此(标题)错误,并希望获得一些帮助。我的withData当前设置的方式是

import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { hasSubscription } from '@jumpn/utils-graphql';
import * as AbsintheSocket from '@absinthe/socket';
import withApollo from 'next-with-apollo';
import { createAbsintheSocketLink } from '@absinthe/socket-apollo-link';
import { Socket as PhoenixSocket } from 'phoenix';

let apolloClient = null;

const HTTP_ENDPOINT = 'http://localhost:4000/api/v1/graphiql';

const WS_ENDPOINT = 'ws://localhost:4000/api/v1/socket';

const httpLink = createHttpLink({
    url: HTTP_ENDPOINT
});

const socketLink = createAbsintheSocketLink(AbsintheSocket.create(new PhoenixSocket(WS_ENDPOINT)));

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

const link = new ApolloLink.split(
    (operation) => hasSubscription(operation.query),
    socketLink,
    authLink.concat(httpLink)
);

const create = (initialState) => {
    return new ApolloClient({
        link: link,
        cache: new InMemoryCache().restore(initialState || {})
    });
};

const initApollo = (initialState) => {
    // Make sure to create a new client for every server-side request so that data
    // isn't shared between connections (which would be bad)
    if (typeof window === 'undefined') {
        return create(initialState);
    }

    // Reuse client on the client-side
    if (!apolloClient) {
        apolloClient = create(initialState);
    }

    return apolloClient;
};

export default withApollo(initApollo);

感谢所有帮助,以了解我做错了什么,并且应该有一种更好的方法。

1 个答案:

答案 0 :(得分:0)

问题是因为nextJs将在服务器中运行上面的代码,并且WebSocket是仅在浏览器中存在的属性,要解决此问题,您可以执行以下操作:

const socketLink =
  process.browser &&
  createAbsintheSocketLink(
    AbsintheSocket.create(
      new PhoenixSocket(WS_URI)
    )
  )

通过检查process.browser,您可以确保仅在客户端执行此功能。