forked from Fascinated/Bat
73 lines
1.9 KiB
Java
73 lines
1.9 KiB
Java
package cc.fascinated.bat.service;
|
|
|
|
import cc.fascinated.bat.model.BatUser;
|
|
import cc.fascinated.bat.repository.UserRepository;
|
|
import lombok.Getter;
|
|
import lombok.NonNull;
|
|
import lombok.extern.log4j.Log4j2;
|
|
import net.jodah.expiringmap.ExpiringMap;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.context.annotation.DependsOn;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.Optional;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
/**
|
|
* @author Fascinated (fascinated7)
|
|
*/
|
|
@Service @Log4j2 @Getter
|
|
@DependsOn("discordService")
|
|
public class UserService {
|
|
/**
|
|
* The cached users
|
|
*/
|
|
private final Map<String, BatUser> users = ExpiringMap.builder()
|
|
.expiration(6, TimeUnit.HOURS)
|
|
.build();
|
|
|
|
/**
|
|
* 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) {
|
|
if (users.containsKey(id)) {
|
|
return users.get(id);
|
|
}
|
|
|
|
long start = System.currentTimeMillis();
|
|
Optional<BatUser> optionalUser = userRepository.findById(id);
|
|
if (optionalUser.isPresent()) {
|
|
BatUser user = optionalUser.get();
|
|
users.put(id, user);
|
|
return user;
|
|
}
|
|
BatUser user = userRepository.save(new BatUser(id));
|
|
log.info("Created user for \"{}\" in {}ms", user.getDiscordUser().getName(), System.currentTimeMillis() - start);
|
|
return user;
|
|
}
|
|
|
|
/**
|
|
* Saves a user
|
|
*
|
|
* @param user The user to save
|
|
*/
|
|
public void saveUser(@NonNull BatUser user) {
|
|
userRepository.save(user);
|
|
}
|
|
}
|