gql-dart / gql

Libraries supporting GraphQL in Dart
MIT License
267 stars 121 forks source link

[Begging for support] Can the url be transformed? #419

Open danielRi opened 11 months ago

danielRi commented 11 months ago

Hi,

I use want to use a WebSocketLink, but for authentication I need to append the current auth token to the url (required by server).

I was thinking about something llike this, but I dont know how to update the url of the request. Can TransformLink achieve this? Im stuck, so any suggestions/help is much appreciated. Thank you!

class WebSocketAuthLink extends Link {
  final Future<String?> Function() getToken;
  final String graphQLEndpoint;

  String? _token;

  late Link _link;

  WebSocketAuthLink({
    required this.getToken,
    required this.graphQLEndpoint,
  }) {
    _link = Link.from([
      WebSocketLink(graphQLEndpoint),
      TransformLink(requestTransformer: transformRequest),
    ]);
  }

  Future<void> updateToken() async {
    _token = await getToken();
    debugPrint('token: ${_token.toString()}');
  }

  Request transformRequest(Request request) {
    // How to update url?
    // final url = oldUrl + _token?
  }

  @override
  Stream<Response> request(Request request, [forward]) async* {
    if (_token == null) {
      await updateToken();
    }

    yield* _link.request(request, forward);
  }
}
knaeckeKami commented 11 months ago

Hi!

If you come to discord (see readme), there was a discussion around something very similar.

You might be able to copy code from that discussion

danielRi @.***> schrieb am Di., 19. Sep. 2023, 11:33:

Hi,

I use want to use a WebSocketLink, but for authentication I need to append the current auth token to the url (required by server).

I was thinking about something llike this, but I dont know how to update the url of the request. Can TransformLink achieve this? Im stuck, so any suggestions/help is much appreciated. Thank you!

class WebSocketAuthLink extends Link { final Future<String?> Function() getToken; final String graphQLEndpoint;

String? _token;

late Link _link;

WebSocketAuthLink({ required this.getToken, required this.graphQLEndpoint, }) { _link = Link.from([ WebSocketLink(graphQLEndpoint), TransformLink(requestTransformer: transformRequest), ]); }

Future updateToken() async { _token = await getToken(); debugPrint('token: ${_token.toString()}'); }

Request transformRequest(Request request) { // How to update url? // final url = oldUrl + _token? }

@override Stream request(Request request, [forward]) async* { if (_token == null) { await updateToken(); }

yield* _link.request(request, forward);

} }

— Reply to this email directly, view it on GitHub https://github.com/gql-dart/gql/issues/419, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAKASNZK3JA5VNMBRKPTJE3X3FRGFANCNFSM6AAAAAA46ACCIY . You are receiving this because you are subscribed to this thread.Message ID: @.***>

danielRi commented 11 months ago

Cool Ill drop by.