fresh icon indicating copy to clipboard operation
fresh copied to clipboard

[fresh_graphql] Link for Subscription

Open Fintasys opened this issue 3 years ago • 4 comments

Great idea this package and exactly what I was looking for. 🙇 Based on this idea it would be possible to create a similar link implementation for subscription.

What do you think?

This is my current code that could be replaced

class WSLink extends Link {
  /// Creates a new [WebSocketLink] instance with the specified config.
  WSLink(
    this.url, {
    this.headers = const {},
    this.getToken,
  });

  final String url;
  final Map<String, dynamic> headers;
  final Future<String?>? getToken;

  // cannot be final because we're changing the instance upon a header change.
  SocketClient? _socketClient;

  @override
  Stream<Response> request(Request request, [forward]) async* {
    // Get Token or Refresh
    if (getToken != null) {
      var token = await getToken;
      headers['Authorization'] = 'Bearer $token';
    }

    if (_socketClient == null) {
      connectOrReconnect();
    }

    yield* _socketClient!.subscribe(request, true);
  }

  /// Connects or reconnects to the server with the specified headers.
  void connectOrReconnect() {
    _socketClient?.dispose();
    _socketClient = SocketClient(
      url,
      config: SocketClientConfig(
        inactivityTimeout: Duration(seconds: 30),
        delayBetweenReconnectionAttempts: const Duration(seconds: 2),
        autoReconnect: true,
        connect: (url, protocols) => IOWebSocketChannel.connect(
          url,
          protocols: protocols,
          headers: headers,
        ),
      ),
    );
  }

  /// Disposes the underlying socket client explicitly. Only use this, if you want to disconnect from
  /// the current server in favour of another one. If that's the case, create a new [WebSocketLink] instance.
  Future<void> dispose() async {
    await _socketClient?.dispose();
    _socketClient = null;
  }
}

Fintasys avatar Jun 27 '21 13:06 Fintasys

Yes, It would be great. I need this also. Thank you.

fikretsengul avatar Jul 02 '21 20:07 fikretsengul

:eyes:

cacianokroth avatar Sep 10 '21 15:09 cacianokroth

It would be nice to have this feature implemented, i'm really struggling to make it work :'(

Centauride avatar Dec 13 '22 16:12 Centauride