如何解决仅在登录后如何创建套接字连接Graphql
我在graphql中使用订阅,该应用程序是在ReactJs + NodeJs + Graphql-Yoga + Graphql-apollo中创建的。根据我在文档中看到的内容,我创建了套接字连接以及创建ApolloClient的文件,但是即使这样,未登录平台的人也可以与后端建立套接字连接。仅在用户登录后如何创建此连接?
apollo配置客户端:
import { ApolloClient,HttpLink,split,InMemoryCache } from "@apollo/client";
import { getMainDefinition } from "@apollo/client/utilities";
import { setContext } from "@apollo/client/link/context";
import { WebSocketLink } from "@apollo/client/link/ws";
const httpLink = new HttpLink({
uri: "http://localhost:4000",credentials: "include",});
const wsLink = new WebSocketLink({
uri: `ws://localhost:4000/`,options: {
reconnect: true,},});
const authLink = setContext((_,{ headers }) => {
const accessToken = window.sessionStorage.getItem("accessToken");
return {
headers: {
...headers,authorization: accessToken ? `Bearer ${accessToken}` : "",};
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},wsLink,authLink.concat(httpLink)
);
const client = new ApolloClient({
link: splitLink,cache: new InMemoryCache(),});
export default client;
服务器端graphql-yoga
const server = new GraphQLServer({
typeDefs: path.resolve(__dirname,"schema.graphql"),resolvers,context: async ({ connection,request }) => {
if (connection) {
return { ...connection,request,pubsub: pubsub };
} else {
return {
pubsub: pubsub,authorization: request.get("authorization"),};
}
},middlewares: [auth],});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。