checkKwikpassHealth static method

Future<Result<HealthCheckResponseData?>> checkKwikpassHealth()

Implementation

static Future<Result<HealthCheckResponseData?>> checkKwikpassHealth() async {
  try {
    final gokwik = DioClient().getClient();

    final results = await Future.wait([
      cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkRequestIdKey)!),
      cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkAccessTokenKey)!),
      cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkMerchantIdKey)!),
    ]);

    final requestId = results[0];
    final accessToken = results[1] ?? "";
    final mid = results[2];

    // Set all headers at once
    final headers = <String, String>{
      cdnConfigInstance.getHeader(APIHeaderKeys.kpMerchantId)!: mid ?? '',
    };

    if(requestId != null && requestId.isNotEmpty){
      headers[cdnConfigInstance.getHeader(APIHeaderKeys.kpRequestId)!] = requestId;
    }

    if (accessToken.isNotEmpty) {
      headers[cdnConfigInstance.getHeader(APIHeaderKeys.gkAccessToken)!] = accessToken;
    }

    gokwik.options.headers.addAll(headers);

    final response = (await gokwik.get(cdnConfigInstance.getEndpoint(APIEndpointKeys.kpHealthCheck)!)).toBaseResponse(
      fromJson: (json) => HealthCheckResponseData.fromJson(json),
    );

    if (response.isSuccess ?? false) {
      final healthData = response.data;
      // Check if kwikpass is healthy
      if (healthData?.isKwikpassHealthy == false) {
        throw KwikpassHealthException();
      }
      return Success(response.data);
    }

    // Throw custom exception when API call fails
    throw KwikpassHealthException();
  } catch (error) {
    if (error is KwikpassHealthException) {
      rethrow; // Re-throw the custom exception
    }
    return Failure(handleApiError(error).message);
  }
}