2024-06-24 13:56:01 +01:00
|
|
|
package cc.fascinated.bat.service;
|
|
|
|
|
2024-06-25 11:55:26 +01:00
|
|
|
import cc.fascinated.bat.model.BatUser;
|
2024-06-24 13:56:01 +01:00
|
|
|
import cc.fascinated.bat.repository.UserRepository;
|
2024-06-27 13:00:45 +01:00
|
|
|
import lombok.Getter;
|
2024-06-24 13:56:01 +01:00
|
|
|
import lombok.NonNull;
|
|
|
|
import lombok.extern.log4j.Log4j2;
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
import org.springframework.context.annotation.DependsOn;
|
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
2024-06-27 13:00:45 +01:00
|
|
|
import java.util.HashMap;
|
|
|
|
import java.util.Map;
|
2024-06-24 13:56:01 +01:00
|
|
|
import java.util.Optional;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @author Fascinated (fascinated7)
|
|
|
|
*/
|
2024-06-27 13:00:45 +01:00
|
|
|
@Service @Log4j2 @Getter
|
2024-06-24 13:56:01 +01:00
|
|
|
@DependsOn("discordService")
|
|
|
|
public class UserService {
|
2024-06-27 13:00:45 +01:00
|
|
|
/**
|
|
|
|
* The cached users
|
|
|
|
*/
|
|
|
|
private final Map<String, BatUser> users = new HashMap<>();
|
|
|
|
|
2024-06-24 13:56:01 +01:00
|
|
|
/**
|
|
|
|
* The user repository to use
|
|
|
|
*/
|
|
|
|
private final UserRepository userRepository;
|
|
|
|
|
|
|
|
@Autowired
|
|
|
|
public UserService(@NonNull UserRepository userRepository) {
|
|
|
|
this.userRepository = userRepository;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets a user by their ID
|
|
|
|
*
|
|
|
|
* @param id The ID of the user
|
|
|
|
* @return The user
|
|
|
|
*/
|
|
|
|
public BatUser getUser(@NonNull String id) {
|
2024-06-27 13:00:45 +01:00
|
|
|
if (users.containsKey(id)) {
|
|
|
|
return users.get(id);
|
|
|
|
}
|
|
|
|
|
2024-06-24 13:56:01 +01:00
|
|
|
long start = System.currentTimeMillis();
|
|
|
|
Optional<BatUser> optionalUser = userRepository.findById(id);
|
|
|
|
if (optionalUser.isPresent()) {
|
2024-06-27 13:00:45 +01:00
|
|
|
BatUser user = optionalUser.get();
|
|
|
|
users.put(id, user);
|
|
|
|
return user;
|
2024-06-24 13:56:01 +01:00
|
|
|
}
|
|
|
|
BatUser user = userRepository.save(new BatUser(id));
|
|
|
|
log.info("Created user \"{}\" in {}ms", id, System.currentTimeMillis() - start);
|
|
|
|
return user;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Saves a user
|
|
|
|
*
|
|
|
|
* @param user The user to save
|
|
|
|
*/
|
|
|
|
public void saveUser(@NonNull BatUser user) {
|
|
|
|
userRepository.save(user);
|
|
|
|
}
|
|
|
|
}
|