2024-04-23 01:15:24 +01:00
|
|
|
package cc.fascinated.backend.service;
|
2024-04-23 00:43:05 +01:00
|
|
|
|
2024-04-23 01:15:24 +01:00
|
|
|
import cc.fascinated.backend.model.Paste;
|
|
|
|
import cc.fascinated.backend.exception.impl.ResourceNotFoundException;
|
|
|
|
import cc.fascinated.backend.repository.PasteRepository;
|
2024-04-23 00:43:05 +01:00
|
|
|
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), 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> 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();
|
|
|
|
}
|
|
|
|
}
|