2023-09-14 01:34:48 +08:00
|
|
|
import {
|
|
|
|
ApolloClient, ApolloProvider, InMemoryCache, NormalizedCacheObject,
|
|
|
|
} from '@apollo/client';
|
2023-04-06 03:18:04 +08:00
|
|
|
// import { WebSocketLink } from "@apollo/client/link/ws";
|
2023-09-14 01:34:48 +08:00
|
|
|
import { WebSocketLink } from '@apollo/client/link/ws';
|
2023-04-06 03:18:04 +08:00
|
|
|
import { SubscriptionClient } from 'subscriptions-transport-ws';
|
|
|
|
import React, { useEffect } from 'react';
|
|
|
|
import Auth from '/imports/ui/services/auth';
|
2023-11-24 21:49:23 +08:00
|
|
|
import { Meteor } from 'meteor/meteor';
|
2023-04-06 03:18:04 +08:00
|
|
|
|
|
|
|
interface Props {
|
|
|
|
children: React.ReactNode;
|
|
|
|
}
|
|
|
|
|
2023-09-14 01:34:48 +08:00
|
|
|
const GraphqlProvider = ({ children }: Props): React.ReactNode => {
|
2023-08-15 04:52:35 +08:00
|
|
|
// const [link, setLink] = React.useState<WebSocketLink | null>(null);
|
2023-04-06 03:18:04 +08:00
|
|
|
const [apolloClient, setApolloClient] = React.useState<ApolloClient<NormalizedCacheObject> | null>(null);
|
|
|
|
useEffect(() => {
|
2023-11-24 21:49:23 +08:00
|
|
|
let GRAPHQL_URL = null;
|
|
|
|
if ('graphqlUrl' in Meteor.settings.public.app) {
|
|
|
|
GRAPHQL_URL = Meteor.settings.public.app.graphqlUrl;
|
|
|
|
} else {
|
|
|
|
GRAPHQL_URL = `wss://${window.location.hostname}/v1/graphql`;
|
|
|
|
}
|
2023-04-06 03:18:04 +08:00
|
|
|
const wsLink = new WebSocketLink(
|
2023-11-24 21:49:23 +08:00
|
|
|
new SubscriptionClient(GRAPHQL_URL, {
|
2023-04-06 03:18:04 +08:00
|
|
|
reconnect: true,
|
|
|
|
timeout: 30000,
|
|
|
|
connectionParams: {
|
|
|
|
headers: {
|
|
|
|
'X-Session-Token': Auth.sessionToken,
|
2023-09-14 01:34:48 +08:00
|
|
|
},
|
|
|
|
},
|
|
|
|
}),
|
2023-04-06 03:18:04 +08:00
|
|
|
);
|
2023-08-15 04:52:35 +08:00
|
|
|
// setLink(wsLink);
|
2023-11-30 00:48:35 +08:00
|
|
|
const client = new ApolloClient({
|
|
|
|
link: wsLink,
|
|
|
|
cache: new InMemoryCache(),
|
|
|
|
connectToDevTools: Meteor.isDevelopment,
|
|
|
|
});
|
2023-04-06 03:18:04 +08:00
|
|
|
setApolloClient(client);
|
|
|
|
}, []);
|
|
|
|
return (
|
2023-09-14 01:34:48 +08:00
|
|
|
apolloClient
|
|
|
|
&& (
|
|
|
|
<ApolloProvider
|
|
|
|
client={apolloClient}
|
|
|
|
>
|
|
|
|
{children}
|
|
|
|
</ApolloProvider>
|
|
|
|
)
|
|
|
|
);
|
2023-04-06 03:18:04 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
export default GraphqlProvider;
|