getCurrentUser method

Future<T?> getCurrentUser()

Retrieve the current logged-in user data.

This method retrieves the data of the current logged-in user. If the user data is cached, it returns the cached data. Otherwise, it sends a GET request to the "user/authenticated/info" endpoint to retrieve the user data.

Returns a Future<T?> that completes with the current user data, or null if no user is logged in.

Implementation

Future<T?> getCurrentUser() async {
  if (CoffeeStorage.getJwtToken().isEmpty) {
    return null;
  }

  if (currentUser != null) {
    return currentUser;
  }

  currentUser = CoffeeStorage.getLoggedUser(fromJson);

  if (currentUser != null) {
    return currentUser;
  }

  if (!currentUserLock) {
    currentUserLock = true;

    final response = getAuthInfo().then((user) async {
      currentUser = user;
      currentUserLock = false;
      await CoffeeStorage.setLoggedUser(currentUser as T);
      return currentUser;
    }).catchError((err) {
      currentUserLock = false;
      currentUser = null;
      return null;
    });

    return response;
  } else {
    // If another request is in progress, wait for it to complete
    // Here, we simply wait for a bit and then recursively call `getCurrentUser` again.
    Future.delayed(const Duration(milliseconds: 50));
    return getCurrentUser();
  }
}