zino-hofmann / graphql-flutter

A GraphQL client for Flutter, bringing all the features from a modern GraphQL client to one easy to use package.
https://zino-hofmann.github.io/graphql-flutter
MIT License
3.24k stars 612 forks source link

GraphQL Subscription constantly connecting and disconnecting #1325

Closed MarlonWiss2212 closed 1 year ago

MarlonWiss2212 commented 1 year ago

Hello, i want to access my GraphQL API with subscriptions. Queries and Mutations just work fine. But when i am trying to connect to my subscription it keeps connecting and disconnecting. My GraphQL server is build with nestjs and it has a console log when someone connects but it doesnt show anything in the logs. However when i do the same thing with Altair everything works just fine. This is my code

import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:graphql/client.dart';

GraphQLClient getGraphQlClient({
  String? token,
  bool websocketEndpoint = false,
}) {
  final HttpLink httpLink = HttpLink(
    "https://${dotenv.get("API_BASE_URL")}/graphql",
    defaultHeaders: {
      "Apollo-Require-Preflight": "true",
      "authorization": "Bearer $token"
    },
  );

  final WebSocketLink webSocketLink = WebSocketLink(
    "wss://${dotenv.get("API_BASE_URL")}/graphql",
    subProtocol: GraphQLProtocol.graphqlWs,
    config: SocketClientConfig(
      inactivityTimeout: const Duration(hours: 1),
      autoReconnect: false,
      initialPayload: {
        'authorization': 'Bearer $token',
      },
    ),
  );

  return GraphQLClient(
    link: Link.split(
      (request) => request.isSubscription,
      webSocketLink,
      httpLink,
    ),
    cache: GraphQLCache(),
    defaultPolicies: DefaultPolicies(
      query: Policies(fetch: FetchPolicy.noCache),
      mutate: Policies(fetch: FetchPolicy.noCache),
      subscribe: Policies(fetch: FetchPolicy.noCache),
    ),
  );
}
I/flutter ( 5577): Initialising connection
I/flutter ( 5577): Disconnected from websocket.
 @override
  Stream<QueryResult<Object?>> subscription(
    String options, {
    Map<String, dynamic> variables = const {},
  }) {
    return client.subscribe(
      SubscriptionOptions(
        document: gql(options),
        variables: variables,
      ),
    );
  }

I have tried putting the toket in the headers but nothing changes. I have tried it now for 2 weeks and have tried many things but nothing works till now. Token and request is definitly fine. Thanks in advance

MarlonWiss2212 commented 1 year ago

I just added autoreconnecting false so that i dont have constantly this error. Now just one time just as shown above

MarlonWiss2212 commented 1 year ago

ok just found out that everything works when you use "subscriptions-transport-ws" in api and frontend but "graphql-ws" only with altair and postman. Really weird but it works