checkVersionWithResponse method

Future<VersionCheckResponse?> checkVersionWithResponse(
  1. PackageInfo packageInfo
)

Check version using the new API format Returns VersionCheckResponse with full API response

Implementation

Future<VersionCheckResponse?> checkVersionWithResponse(
  PackageInfo packageInfo,
) async {
  if (!useNewApiFormat) {
    throw Exception(
      'checkVersionWithResponse requires useNewApiFormat=true. '
      'Use the new constructor with baseUrl and apiKey.',
    );
  }

  try {
    // Get device ID (optional but recommended)
    final deviceId = await _getDeviceId();

    // Get platform
    final platform = _getPlatform();

    // Build URL with query parameters
    // baseUrl already includes /api/v1, so we just append /public/version-check
    final uri = Uri.parse('$baseUrl/public/version-check').replace(
      queryParameters: {
        'bundleId': packageInfo.packageName,
        'versionCode': packageInfo.version,
        'buildNumber': packageInfo.buildNumber,
        'platform': platform,
        if (deviceId != null) 'deviceId': deviceId,
      },
    );

    // Build headers
    final headers = <String, String>{
      'Content-Type': 'application/json',
      if (apiKey != null) 'x-api-key': apiKey!,
      ...?additionalHeaders,
    };

    // Make request
    final response = await http.get(uri, headers: headers);

    // Handle errors
    if (response.statusCode == 401) {
      throw Exception('Invalid API Key');
    } else if (response.statusCode == 403) {
      throw Exception('App is inactive');
    } else if (response.statusCode == 404) {
      throw Exception('App not found for this bundle ID');
    } else if (response.statusCode != 200) {
      throw Exception('Error checking version: ${response.statusCode}');
    }

    // Parse response
    final json = jsonDecode(response.body) as Map<String, dynamic>;
    final versionResponse = VersionCheckResponse.fromJson(json);

    // Only return if there's an update and user is in rollout
    if (versionResponse.hasUpdate && versionResponse.isInRollout == true) {
      return versionResponse;
    }

    return null;
  } catch (e) {
    throw Exception('Failed to check for updates: $e');
  }
}