fetchExperimentRequest function

Future<FormattedExperimentApiResponse?> fetchExperimentRequest({
  1. required String token,
  2. required String uniqueId,
  3. required String? userId,
})

Implementation

Future<FormattedExperimentApiResponse?> fetchExperimentRequest({
  required String token,
  required String uniqueId,
  required String? userId,
}) async {
  try {
    const headers = invalidateCacheHeaders;
    final body = jsonEncode({
      'token': token,
      'userId': userId,
      'uniqueId': uniqueId,
    });
    final request = http
        .post(
          Uri.parse(experimentServiceUrl),
          headers: headers,
          body: body,
        )
        .timeout(const Duration(milliseconds: 10000));

    final response = await request;

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body) as Map<String, dynamic>;
      final experimentApiResponse = ExperimentApiResponse.fromJson(data);
      final experimentData = <String, UserExperimentVariant>{};

      for (var exp in experimentApiResponse.experiments) {
        experimentData[exp.experimentName] = exp;
      }

      final experimentInfo = FormattedExperimentApiResponse(
        experimentData: experimentData,
        experimentUserType: experimentApiResponse.userType,
        timestamp: DateTime.now().millisecondsSinceEpoch,
      );
      return experimentInfo;
    } else {
      Debug.print('Experiment Service: Failed to fetch experiment data');
      return null;
    }
  } catch (error) {
    Debug.print('Experiment Service: Failed to fetch experiment data: $error');
    return null;
  }
}