haz*_*haz 5 typescript apollo reactjs next.js apollo-client
我是 NextJS 的新手。我有一个页面需要显示从 Hasura GraphQL 后端提取的实时数据。
在其他非 NextJS 应用程序中,我将 GraphQL 订阅与 Apollo 客户端库结合使用。在幕后,这使用了 websocket。
当不使用订阅时,我可以让 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);
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
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>
}
Run Code Online (Sandbox Code Playgroud)
但是,我想这样做:
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>
}
Run Code Online (Sandbox Code Playgroud)
我尝试过的
我尝试在 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);
Run Code Online (Sandbox Code Playgroud)
但是当我加载页面时,我Internal Server Error在终端中收到一个 , 和此错误:
Error: Unable to find native implementation, or alternative implementation for WebSocket!
Run Code Online (Sandbox Code Playgroud)
在我看来,ApolloClient然后是在服务器端生成的,其中没有 WebSocket 实现。我怎样才能在客户端实现这一点?
找到了使其工作的解决方法,请查看此答案https://github.com/apollographql/subscriptions-transport-ws/issues/333#issuecomment-359261024
原因是由于服务器端渲染;这些语句必须在浏览器中运行,因此我们测试是否有process.browser!
所附 github 链接中的相关部分:
const wsLink = process.browser ? new WebSocketLink({ // if you instantiate in the server, the error will be thrown
uri: `ws://localhost:4000/subscriptions`,
options: {
reconnect: true
}
}) : null;
const httplink = new HttpLink({
uri: 'http://localhost:3000/graphql',
credentials: 'same-origin'
});
const link = process.browser ? split( //only create the split in the browser
// split based on operation type
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httplink,
) : httplink;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9645 次 |
| 最近记录: |