getAuthInfo method

Future<T?> getAuthInfo()

Retrieves authentication information of the user.

This method sends a GET request to the 'user/authenticated/info' endpoint and expects a JSON response that it converts to an object of type T using the provided fromJson function.

Query parameters can be appended to the request URL, and the method tries to restore saved data for the user.

Returns a Future<T> that completes with the authenticated user data.

Implementation

Future<T?> getAuthInfo() async {
  var url = CoffeeUtil.concatUrl(_baseEndpoint, 'user/authenticated/info');

  // Append query parameters to the URL
  if (_queryParams.isNotEmpty) {
    final queryString = _queryParams.entries
        .map((e) => '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
        .join('&');
    url = '$url?$queryString';
  }

  try {
    // Send GET request
    final response = await http.get(Uri.parse(url), headers: {
      HttpHeaders.authorizationHeader: CoffeeStorage.getJwtToken()
    });

    // Check if the request was successful
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body) as Map<String, dynamic>;

      // Convert JSON to object of type T
      currentUser = fromJson(data);

      // Try to restore saved data
      if (currentUser != null) {
        final keys = (currentUser as Map<String, dynamic>).keys;

        for (final key in keys) {
          final storageValue = CoffeeStorage.getUserProperty(currentUser!, key);

          if (storageValue != null) {
            (currentUser as dynamic)[key] = storageValue;
            currentUser = fromJson(currentUser as Map<String, dynamic>);
          }
        }
      }
    }
  // ignore: empty_catches
  } catch (e) {}

  return currentUser;
}