Search code examples
flutterdartgraphqldioferry

Graphql Flutter Ferry How to get headers from the response


I'm using Ferry for some queries that I'm making to my GraphQL server. A problem that I'm having is I need to be able to get the access token/refresh token from the cookie/headers. I'm not seeing a way of accessing the headers in the response with ferry.

Current Code:

  @override
  Stream<OperationResponse<TData, TVars>> request<TData, TVars>(
      OperationRequest<TData, TVars> request) {
    try {
      Stream<OperationResponse<TData, TVars>> response = _client.request<TData, TVars>(request);
      response.first.then((requestResponse) {
          final headers = requestResponse // I want to get the headers here somehow but don't see a way.
        
        final authorization = headers?['authorization']?.firstOrNull;
        final cookie = headers?['set-cookie']?.firstOrNull;

        if (authorization != null) {
          _authToken = authorization;
          _securedStorageService.saveAuthToken(authorization);
        }

        if (cookie != null) {
          _refreshToken = cookie;
          _securedStorageService.saveRefreshToken(cookie);

          final maxAge = cookie.split(';').firstWhere(
            (element) => element.contains('Max-Age'),
            orElse: () => '',
          );

          if (maxAge.isNotEmpty) {
            final expirationSeconds = maxAge.split('=').last;
            final expires = DateTime.now().add(Duration(seconds: int.parse(expirationSeconds)));
            _tokenExpired = expires.isBefore(DateTime.now());
            _securedStorageService.saveRefreshTokenExpiration(expires.toIso8601String());
          }
        }

        return requestResponse;
      });
      return response;
    } catch (e) {
      rethrow; // We want to handle errors in the repository layer not here in this lower service layer.
    }
  }

I have looked at the available types on the OperationResponse type but not seeing anyway of accessing the response headers


Solution

  • Just found a solution:

    if you are using DIO like I am you can just add a Dio interceptor.

        final dio = Dio();
        dio.interceptors.add(
          InterceptorsWrapper(
            onResponse: (response, handler) {
              _handleResponse(response); // Here I am adding a handler that saves my token
              return handler.next(response);
            },
            onError: (error, handler) {
              debugPrint('Http error: ${error.message}');
              return handler.next(error);
            },
          ),
        );