refreshTokenCallback<T> method

Future<Response<T>?> refreshTokenCallback<T>(
  1. RequestOptions requestOptions, [
  2. RequestInterceptorHandler? handler
])

Refreshes the token and retries the request with the new token.

This is called by RefreshTokenInterceptor when a token refresh is needed.

If handler is provided (from interceptor), it will call handler.next() to continue the interceptor chain. Otherwise, it executes the request directly and returns the response.

Returns null if token resolvers are not configured.

Implementation

Future<Response<T>?> refreshTokenCallback<T>(
  RequestOptions requestOptions, [
  RequestInterceptorHandler? handler,
]) async {
  if (authOptions.resolveJwt != null &&
      authOptions.resolveRefreshToken != null) {
    await executeTokenRefresh();

    final currentJwt = await jwt;

    if (requestOptions.headers.containsKey(RestApiClientKeys.authorization)) {
      requestOptions.headers.update(
        RestApiClientKeys.authorization,
        (v) => 'Bearer $currentJwt',
      );
    } else {
      requestOptions.headers.addAll({
        RestApiClientKeys.authorization: 'Bearer $currentJwt',
      });
    }

    if (handler != null) {
      handler.next(requestOptions);
    } else {
      return await dio.request(
        requestOptions.path,
        cancelToken: requestOptions.cancelToken,
        data: requestOptions.data,
        onReceiveProgress: requestOptions.onReceiveProgress,
        onSendProgress: requestOptions.onSendProgress,
        queryParameters: requestOptions.queryParameters,
        options: Options(
          method: requestOptions.method,
          sendTimeout: requestOptions.sendTimeout,
          receiveTimeout: requestOptions.receiveTimeout,
          extra: requestOptions.extra,
          headers: requestOptions.headers,
          responseType: requestOptions.responseType,
          contentType: requestOptions.contentType,
          validateStatus: requestOptions.validateStatus,
          receiveDataWhenStatusError:
              requestOptions.receiveDataWhenStatusError,
          followRedirects: requestOptions.followRedirects,
          maxRedirects: requestOptions.maxRedirects,
          requestEncoder: requestOptions.requestEncoder,
          responseDecoder: requestOptions.responseDecoder,
          listFormat: requestOptions.listFormat,
        ),
      );
    }
  }

  return null;
}