package cc.fascinated.backend.service; import cc.fascinated.backend.model.Paste; import cc.fascinated.backend.exception.impl.ResourceNotFoundException; import cc.fascinated.backend.repository.PasteRepository; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class PasteService { /** * The {@link PasteRepository} instance. */ private final PasteRepository pasteRepository; /** * The length of the paste id. */ @Value("${paste.id-length}") private int idLength; @Autowired public PasteService(PasteRepository pasteRepository) { this.pasteRepository = pasteRepository; } /** * Creates a new paste with the specified content. * * @param content The content of the paste. * @return The id of the paste. */ public String createPaste(String content) { return pasteRepository.save(new Paste( RandomStringUtils.randomAlphabetic(idLength), System.currentTimeMillis(), content )).getId(); } /** * Gets the content of the paste with the specified id. * * @param id The id of the paste. * @return The content of the paste. */ public Paste getPaste(String id) { Optional paste = pasteRepository.findById(id); // The paste does not exist. if (paste.isEmpty()) { throw new ResourceNotFoundException("Paste with id '%s' not found".formatted(id)); } return paste.get(); } }