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.25k stars 623 forks source link

[feature] add an easy way to add headers #1382

Closed subzero911 closed 9 months ago

subzero911 commented 1 year ago

I would like to have an option to easily add custom headers to requests. The syntax I want to see:

final response = await authGqlClient!.mutate_BindChildCard(
      Options_Mutation_BindChildCard(
        headers: {
            'X-Testing': '1',
            'X-Testing-Try-Mock': 'BankCardsRequest;BankTokensRequest;BankDetailsRequest;BankBalanceRequest'
          },
        variables: Variables_Mutation_BindChildCard(
          input: Input_BindChildCardInput(
            cardId: cardId,
            childId: childId,
            userId: GetIt.I<UserController>().user!.id,
          ),
        ),
      ),
    );

Currently the only way to add headers it to add it on graphql client init:

image

I can't change headers afterwards for individual requests.

ming-chu commented 10 months ago

@subzero911 Maybe consider using a custom HttpClient for it:

  final httpLink = HttpLink(
    baseUrl,
    httpClient: YourHttpClient(),
  );
class YourHttpClient extends http.BaseClient {
  final http.Client _client;

  YourHttpClient({http.Client? client}) : _client = client ?? http.Client();

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    request.headers.addAll({
      'X-Testing': '1',
      'X-Testing-Try-Mock': 'BankCardsRequest;',
    });
    return _client.send(request);
  }
}

Hope it helps.

subzero911 commented 10 months ago

Thanks, but it wouldn't help. We still add a HttpClient on a HttpLink creation stage and can't change it afterwards. So it won't be much different from the problem described in a starting post (even more code). I would like to see the easier way, without having to create a custom HttpClient just in order to add headers.

ming-chu commented 10 months ago

Just for a workaround ... When you have a HttpClient with control then you can change it if you want to. Some sudo code here for your reference:

  final yourHttpClient = YourHttpClient();
  yourHttpClient.setHeader(xxxx);

  final httpLink = HttpLink(
    baseUrl,
    httpClient: yourHttpClient,
  );

 //....
  yourHttpClient.setHeader(xxxx);
  // your query here ...
ming-chu commented 10 months ago

maybe consider using Context when query🤔

     final options = QueryOptions(
      // .....
      context: Context.fromList([
        HttpLinkHeaders(headers: {
          'X-Testing': '1',
          'X-Testing-Try-Mock': 'BankCardsRequest;',
        })
      ]),
    );
subzero911 commented 10 months ago

Looks like a solution

ming-chu commented 9 months ago

Looks like a solution

Please close the issue if you think it's already solved.