apollographql / graphql-subscriptions

:newspaper: A small module that implements GraphQL subscriptions for Node.js
MIT License
1.59k stars 133 forks source link

Subscription doesn't work #206

Closed AmirBraham closed 5 years ago

AmirBraham commented 5 years ago

Subscriptions works in the playground but not in apollo graphql client . here's the query being used in both the playground and client :

export const PARTY_SUBSCRIPTION = gql`
  subscription onPartyUpdated($hostname: String!) {
    party(hostname: $hostname) {
      mutation
      node {
        id
        users {
          username
        }
        open
        hostname
      }
    }
  }
`;

And this is my apollo client config file :

const DEV_DB_ENDPOINT = "http://192.168.1.3:4000/";

const authLink = setContext(async (_, { headers }) => {
  const token = await AsyncStorage.getItem("userToken");
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ""
    }
  };
});

const wsLink = new WebSocketLink({
  uri: "ws://localhost:5000/",
  options: {
    reconnect: true
  }
});
const httpLink = new HttpLink({
  uri: DEV_DB_ENDPOINT,
  credentials: "same-origin"
});

const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    console.log(query);
    return (
      definition.kind === "OperationDefinition" &&
      definition.operation === "subscription"
    );
  },
  wsLink,
  httpLink
);

const client = new ApolloClient({
  link: ApolloLink.from([
    onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors)
        graphQLErrors.map(({ message, locations, path }) =>
          console.log(
            `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
          )
        );

      if (networkError) console.log(`[Network error]: ${networkError}`);
    }),
    authLink,
    link
  ]),
  cache: new InMemoryCache()
});

export { client };

and this is my subscription component

<Subscription
  subscription={PARTY_SUBSCRIPTION}
  variables={{
    hostname: "Amir004"
  }}
  onError={err => console.log(err)}
  onCompleted={data => console.log(data)}
>
  {() => {
    return <Text>Current list of friends in your party : </Text>;
  }}
</Subscription>

Any help is really appreciated :)

AmirBraham commented 5 years ago

For anyone still struggling with this problem , using Query component and calling subscribeToMore seems to work ! I still don't know what's the source issue and currently , I can only subscribe using a query component ! For more info on subscribeToMore : https://www.apollographql.com/docs/react/advanced/subscriptions/#subscribetomore