execute method

void execute(
  1. dynamic onComplete(
    1. ApiResponseModel? apiResponseModel
    ),
  2. dynamic onErrorRefreshTokenExpired(
    1. String
    ), {
  3. dynamic forceNewToken = false,
})

Implementation

void execute(Function(ApiResponseModel? apiResponseModel) onComplete,
    Function(String) onErrorRefreshTokenExpired,
    {forceNewToken = false}) async {
  ApiResponseModel? apiResponseModel =
      _cacheApiResponseUseCase.getApiResponseModel();
  int? expiredIn = apiResponseModel?.expressToken?.expiredIn;
  int? requestedAt = apiResponseModel?.expressToken?.requestedAt;
  if (!forceNewToken && expiredIn != null && requestedAt != null) {
    int nowInMilliseconds = DateTime.now().millisecondsSinceEpoch;
    int lastTokenRequestPlusDelta =
        requestedAt + REQUEST_DELTA_IN_MILLISECONDS;
    bool tokenHasExpired =
        expiredIn < (nowInMilliseconds - lastTokenRequestPlusDelta);
    if (!tokenHasExpired) {
      YLog.d(
          "Y-Auth: GetAccessTokenUseCase:: Token is still valid ${apiResponseModel}");
      onComplete(apiResponseModel);
      return;
    } else {
      YLog.d("Y-Auth: GetAccessTokenUseCase: Access Token has expired");
    }
  } else {
    YLog.d(
        "Y-Auth: GetAccessTokenUseCase: First Launch or Access Token has been force to update");
  }

  String refreshToken = await _preferencesDatasource.getRefreshToken();

  if (refreshToken.isNotEmpty) {
    AuthResponse authResponse =
        await _requestAccessTokenUseCase.execute(refreshToken);
    switch (authResponse) {
      case ErrorResponse():
        int statusCode = authResponse.statusCode;
        if (statusCode == 401) {
          _signOutUseCase.execute();
          onErrorRefreshTokenExpired("Refresh Token has expired");
          return;
        }
        break;

      case SuccessResponse():
        try {
          apiResponseModel =
              ApiResponseModel.fromJson(json.decode(authResponse.body));
          _cacheApiResponseUseCase.update(apiResponseModel);
        } catch (e) {
          YLog.d("GetNewAccessToken: Token Model exception: ${e}");
        }
        break;
    }
  } else {
    onErrorRefreshTokenExpired("No Refresh token found");
    return;
  }

  onComplete(apiResponseModel);
}