This repository has been archived on 2024-06-10. You can view files and clone it, but cannot push or open issues or pull requests.
Files
Backend/src/main/java/cc/fascinated/backend/service/PasteService.java

62 lines
1.7 KiB
Java
Raw Normal View History

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) {
2024-04-23 03:36:14 +01:00
return pasteRepository.save(new Paste(
RandomStringUtils.randomAlphabetic(idLength),
System.currentTimeMillis(),
content
)).getId();
2024-04-23 00:43:05 +01:00
}
/**
* 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();
}
}