SettingsService.java

  1. package no.nav.data.team.settings;

  2. import com.fasterxml.jackson.databind.node.JsonNodeFactory;
  3. import com.github.benmanes.caffeine.cache.Caffeine;
  4. import com.github.benmanes.caffeine.cache.LoadingCache;
  5. import lombok.RequiredArgsConstructor;
  6. import no.nav.data.common.storage.domain.GenericStorage;
  7. import no.nav.data.common.storage.domain.GenericStorageRepository;
  8. import no.nav.data.common.storage.domain.TypeRegistration;
  9. import no.nav.data.common.utils.JsonUtils;
  10. import no.nav.data.common.validator.Validator;
  11. import no.nav.data.team.settings.dto.Settings;
  12. import org.springframework.stereotype.Service;

  13. import java.time.Duration;
  14. import java.util.UUID;

  15. @Service
  16. @RequiredArgsConstructor
  17. public class SettingsService {

  18.     private static final String SETTINGS = TypeRegistration.typeOf(Settings.class);
  19.     private final GenericStorageRepository repository;

  20.     private final LoadingCache<String, Settings> cache = Caffeine.newBuilder()
  21.             .expireAfterWrite(Duration.ofMinutes(1))
  22.             .build(k -> getSettings());

  23.     public Settings getSettings() {
  24.         return findSettings().getDomainObjectData(Settings.class);
  25.     }

  26.     public Settings getSettingsCached() {
  27.         return cache.get("singleton");
  28.     }

  29.     public Settings updateSettings(Settings settings) {
  30.         Validator.validate(settings);
  31.         GenericStorage settingsStorage = findSettings();
  32.         settingsStorage.setData(JsonUtils.toJsonNode(settings));
  33.         Settings updated = repository.save(settingsStorage).getDomainObjectData(Settings.class);
  34.         cache.put("singleton", updated);
  35.         return updated;
  36.     }

  37.     private GenericStorage findSettings() {
  38.         return repository.findByType(SETTINGS).orElseGet(this::createSettings);
  39.     }

  40.     private GenericStorage createSettings() {
  41.         return repository.save(new GenericStorage(UUID.randomUUID(), SETTINGS, JsonNodeFactory.instance.objectNode()));
  42.     }

  43. }