fetchWithAuth method
액세스 토큰을 붙여 요청하고 401이면 토큰 갱신 후 최대 두 번 재시도한다.
Implementation
Future<http.Response> fetchWithAuth(
String path, {
Map<String, dynamic>? queryParameters,
String method = "GET",
Map<String, String>? headers,
Object? body,
int count = 0,
}) async {
final accessToken = DN.secureStorage.findAccessToken();
final authHeaders = {
if (accessToken != null) "Authorization": "Bearer $accessToken",
...?headers,
};
final response = await fetch(
path,
queryParameters: queryParameters,
method: method,
headers: authHeaders,
body: body,
);
if (!response.isUnauthorized) {
return response;
}
if (count >= 2) {
DN.log("Max retry attempts reached. Returning unauthorized response.");
return response;
}
DN.log("Access token expired. Trying to refresh...");
if (!await _refreshSession()) {
return response;
}
DN.log("Access token refreshed. Retrying the original request...");
return fetchWithAuth(
path,
queryParameters: queryParameters,
method: method,
headers: headers,
body: body,
count: count + 1,
);
}