我正在使用 Ferry 来对 GraphQL 服务器进行一些查询。我遇到的一个问题是我需要能够从 cookie/标头获取访问令牌/刷新令牌。我没有看到使用 ferry 访问响应中标头的方法。
当前代码:
@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.
}
}
我已经查看了 OperationResponse 类型上的可用类型,但没有看到访问响应标头的方法
刚刚找到解决方案:
如果你像我一样使用DIO,你可以添加一个Dio拦截器。
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);
},
),
);