createUserApi static method

Future<Result<Map<String, dynamic>?>> createUserApi({
  1. required String email,
  2. required String name,
  3. String? dob,
  4. String? gender,
})

Implementation

static Future<Result<Map<String, dynamic>?>> createUserApi({
  required String email,
  required String name,
  String? dob,
  String? gender,
}) async {
  final result = await checkKwikpassHealth();
  if (result.isSuccess) {
    final healthData = result.getDataOrThrow();
    if (healthData?.isKwikpassHealthy == false) {
      throw KwikpassHealthException();
    }
  }

  try {
    final gokwik = DioClient().getClient();

    final response = (await gokwik.post(
      cdnConfigInstance.getEndpoint(APIEndpointKeys.customCreateUser)!,
      data: {
        'email': email,
        'name': name,
        if (dob != null) 'dob': dob,
        if (gender != null) 'gender': gender,
      },
    )).toBaseResponse(fromJson: (json) => json);

    if (response.isSuccess == false) {
      return Failure(response.errorMessage ?? 'Failed to create user');
    }

    final data = response.data;
    final merchantResponse = data?['merchantResponse'];
    final user = _extractMerchantUser(merchantResponse);

    if (user == null) {
      final accountErrors = merchantResponse?['accountCreate']?['accountErrors'];
      if (accountErrors != null && (accountErrors as List).isNotEmpty) {
        throw accountErrors[0];
      }
      throw Exception('Email already exists.');
    }

    final userRes = {
      'email': email,
      'username': name,
      'dob': dob,
      'gender': gender,
      'isSuccess': true,
      'emailRequired': true,
      'merchantResponse': {
        'csrfToken': user['csrfToken'],
        'id': user['id'],
        'token': user['token'],
        'refreshToken': user['refreshToken'],
        'email': email,
        if (merchantResponse is Map)
          ...Map<String, dynamic>.from(merchantResponse),
      },
    };

    await cacheInstance.setValue(
      cdnConfigInstance.getKeys(StorageKeyKeys.gkVerifiedUserKey)!,
      jsonEncode(userRes),
    );

    return Success(userRes);
  } catch (err) {
    throw handleApiError(err);
  }
}