Salal Haider
Salal Haider

Reputation: 1

GraphQl subscription throwing exception when subscribing with Apollo server flutter

GraphQl subscription throwing exception "web socket connect failed" when subscribing with Apollo server. Subscription is working fine with graphQl explorer but failing when implemented in flutter

Code and exceptions are attached below.

********** Code ***********

final _wsLink = WebSocketLink(    
  ‘***************’,    
  config: SocketClientConfig(
    autoReconnect: true,
    inactivityTimeout: Duration(hours: 1),
    // delayBetweenReconnectionAttempts: Duration(seconds: 1),
  ),  
); 

final Link _link = Link.split((request) => request.isSubscription, _wsLink, httpLink);
     
client = GraphQLClient(     
  cache: GraphQLCache(store: InMemoryStore()),
  link: _link,  
);

SubscriptionOptions options = SubscriptionOptions(
  document: gql(query),
  variables: variables);

final result = client.subscribe(options);

result.listen((event) {
  print("Event fired ${event.data}");
  print("Event fired ${event.exception?.graphqlErrors.toString()}");
}).onError((e) {
  print("Received Error ! ${e.toString()}");
});

return result;

************ Exception ***************

I/flutter ( 5204): Disconnected from websocket.

Upvotes: 0

Views: 382

Answers (1)

Arjun Mahar
Arjun Mahar

Reputation: 367

I'm late but this works for me, if you have Apollo Server 4

final HttpLink httpLink = HttpLink(
    'http://192.168.43.29:4000/graphql', // my localhhost
  );
  
   final AuthLink authLink = AuthLink(
      getToken: () async => 'Bearer $token',
    );
    Link link = authLink.concat(httpLink);

    WebSocketLink websocketLink = WebSocketLink(
      'ws://192.168.43.29:4000/graphql/subscriptions', // my localhhost
      config: SocketClientConfig(
          autoReconnect: true,
          inactivityTimeout: const Duration(seconds: 30),
          initialPayload: {
            'token': token,
          },
          ),
      subProtocol: GraphQLProtocol.graphqlTransportWs, // This line is important, by default protocol is GraphQLProtocol.graphqlWs
    );

    if (websocketLink != null) {
      link =
          Link.split((request) => request.isSubscription, websocketLink, link);
    }

    graphqlClient = ValueNotifier(
      GraphQLClient(
        link: link,
        cache: GraphQLCache(store: HiveStore()),
      ),
    );

Upvotes: 0

Related Questions