WordRepository.java (1729B)
1 package com.wimdupont.client; 2 3 import com.fasterxml.jackson.core.JsonProcessingException; 4 import com.fasterxml.jackson.databind.ObjectMapper; 5 import com.wimdupont.config.ApplicationProperties; 6 import com.wimdupont.model.db.WordCouchDocument; 7 import com.wimdupont.model.db.WordSelectorResponse; 8 import com.wimdupont.model.dto.WordDto; 9 10 import java.util.ArrayList; 11 import java.util.List; 12 import java.util.Optional; 13 14 15 public class WordRepository { 16 17 private final ApplicationProperties applicationProperties = ApplicationProperties.getInstance(); 18 19 public List<String> findAllWords() { 20 return Client.get(applicationProperties.getCouchdbUrl() + "/_all_docs?include_docs=true", WordCouchDocument.class) 21 .map(wordCouchDocument -> wordCouchDocument.rows().stream().map(row -> row.doc().word()).toList()) 22 .orElseGet(ArrayList::new); 23 } 24 25 public Optional<WordDto> findByWord(String word) { 26 var url = applicationProperties.getCouchdbUrl() + "/_find"; 27 var requestString = String.format("{ \"selector\": { \"word\": { \"$eq\": \"%s\" } } }", word); 28 return Client.post(url, WordSelectorResponse.class, requestString).flatMap(f -> f.docs().stream().findAny()); 29 } 30 31 public void save(WordDto wordDto) { 32 if (findByWord(wordDto.word()).isEmpty()) { 33 var url = applicationProperties.getCouchdbUrl(); 34 try { 35 Client.post(url, WordSelectorResponse.class, new ObjectMapper().writeValueAsString(wordDto)); 36 } catch (JsonProcessingException e) { 37 throw new RuntimeException(e); 38 } 39 } else { 40 System.out.printf("Word %s already saved", wordDto.word()); 41 } 42 } 43 }