Pap*_*ete 8 websocket graphql next.js apollo-client
因此,我有一个用 Go 编写的 GraphQL 服务器,非常严格地遵循本教程。我将前端编写为 Next.js 应用程序,目前正在尝试创建一个客户端来连接到我的服务器,即使遵循T 的订阅文档,我似乎也无法让它工作。为什么提供的示例不包含webSocketImpl?
如果我不提供webSocketImpl,我会得到:
Error: WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`
Run Code Online (Sandbox Code Playgroud)
所以,自然地,我import { WebSocket } from "ws";,并且有:
const wsLink = new GraphQLWsLink(
createClient({
webSocketImpl: WebSocket,
url: "ws://localhost:8080/subscriptions",
})
);
Run Code Online (Sandbox Code Playgroud)
然后我得到:
error - ./node_modules/node-gyp-build/index.js:1:0
Module not found: Can't resolve 'fs'
Run Code Online (Sandbox Code Playgroud)
这是完整的代码,基本上我需要的只是创建一个 ApolloClient 并将其导出以在我的 React 代码中使用。
import { ApolloClient, HttpLink, InMemoryCache, split } from "@apollo/client";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";
import { getMainDefinition } from "@apollo/client/utilities";
import { WebSocket } from "ws";
const wsLink = new GraphQLWsLink(
createClient({
webSocketImpl: WebSocket,
url: "ws://localhost:8080/subscriptions",
})
);
const httpLink = new HttpLink({
uri: `http://localhost:8080/query`,
});
const link = split(
({ query }) => {
const def = getMainDefinition(query);
return (
def.kind === "OperationDefinition" && def.operation === "subscription"
);
},
wsLink,
httpLink
);
export const Client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
Run Code Online (Sandbox Code Playgroud)
我在这里完全错过了什么吗?我的安装中是否没有默认的 WebSocket 实现?显然,该"ws"实现并没有削减它,可能是因为fs在浏览器中不可用?
Pap*_*ete 22
我在这里遗漏了一件重要的事情:我正在使用 Next.js。发生这种情况的原因是SSR。基本上,如果我们在浏览器中使用“typeof window !== 'undefined'”,我们只需要生成 WebSocket 链接。这是我更新的代码:
import { ApolloClient, HttpLink, InMemoryCache, split } from "@apollo/client";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";
import { getMainDefinition } from "@apollo/client/utilities";
const wsLink =
typeof window !== "undefined"
? new GraphQLWsLink(
createClient({
url: "ws://localhost:8080/subscriptions",
})
)
: null;
const httpLink = new HttpLink({
uri: `http://localhost:8080/query`,
});
const link =
typeof window !== "undefined" && wsLink != null
? split(
({ query }) => {
const def = getMainDefinition(query);
return (
def.kind === "OperationDefinition" &&
def.operation === "subscription"
);
},
wsLink,
httpLink
)
: httpLink;
export const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5688 次 |
| 最近记录: |