I hope you are doing well!
We are trying to implement web sockets in our website and we are using Apollo/Client v3 for the client side. Everything is working perfectly except for the subscription.
Here is the code for my client:
import { ApolloClient, InMemoryCache, split } from "@apollo/client";
import { getMainDefinition } from "@apollo/client/utilities";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";
import { HttpLink } from "apollo-link-http";
import { link, socketLink } from "./gql-link";
const httpLink = new HttpLink({
uri: link,
});
const wsLink = new GraphQLWsLink(
createClient({
uri: socketLink,
})
);
const splitLink = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === "OperationDefinition" && operation === "subscription";
},
wsLink,
httpLink
);
const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
export default client;
the url used are:
export const link="http://dummydomain/backend/graphql/graphql";
export const socketLink = "ws://dummydomain/backend/graphql/graphql"
and here is the code for my subscription:
const { subData } = useSubscription(
ON_UPDATE_STATIONS,
{
variables: {
req: {
enableFilters: true,
filters: filtersState,
keys: {
page: page + 1,
pageSize: rowsPerPage,
},
siteID: fromSites ? siteGuid : null,
keyword: search,
orderColumn: orderColumn,
orderDirection: orderDirection,
//noSitesStations: false,
userID: storeUserGuid,
},
}
}
);
and here is my subscription:
export const ON_UPDATE_STATIONS = gql`
subscription ($req: GetStationsListModelInput!) {
onUpdateStationSubscription(model: $req) {
stationsListModel {
stations {
stationGuid
stationStatus {
description
}
}
totalNumberOfRecords
}
errorMessage
errorCode
}
}
`;
Whenever I open the page the subscription is on, I get the following error in the console
POST http://dummydomain/backend/graphql/graphql 500 (Internal Server Error)
I tried using the subscribeToMore
property this way instead of the useSubscription
subscribeToMore({
document: ON_UPDATE_STATIONS,
updateQuery: (prev, { subscriptionData }) => {
console.log(prev, subscriptionData)
}
});
and I got an additional error in the console
Unhandled GraphQL subscription error ServerError: Response not successful: Received status code 500
We are using the same links for web (React) and mobile (Flutter), and with flutter, the websocket is working so I don’t think is it because of the server. What could be the problem? I followed the entire Apollo/Client documentation on useSubscription
.