mirror of
https://github.com/spring-projects/spring-petclinic.git
synced 2025-07-26 01:15:50 +00:00
🚧 validate patient ID
This commit is contained in:
parent
7de04e2939
commit
00b0bb10bd
1 changed files with 21 additions and 8 deletions
|
@ -4,7 +4,6 @@ import java.io.IOException;
|
|||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
import javax.sql.DataSource;
|
||||
|
@ -12,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@Controller
|
||||
class RecordsTransferController {
|
||||
|
@ -27,20 +27,33 @@ class RecordsTransferController {
|
|||
}
|
||||
|
||||
@PostMapping("/records-transfers")
|
||||
public NewRecordModel newRecordsTransfer(@RequestBody InputStream body) throws IOException, SQLException {
|
||||
public NewRecordModel newRecordsTransfer(@RequestParam final String patientId, @RequestBody final InputStream body)
|
||||
throws IOException, SQLException {
|
||||
validatePatientId(patientId);
|
||||
final var id = saveToRecordsSystem(body);
|
||||
return new NewRecordModel(id);
|
||||
}
|
||||
|
||||
private String saveToRecordsSystem(final InputStream is) throws IOException, SQLException {
|
||||
/**
|
||||
* @param patientId id of the patient
|
||||
* @throws SQLException when there is a problem with the database
|
||||
* @throws IllegalArgumentException when the patient does not exist
|
||||
*/
|
||||
private void validatePatientId(final String patientId) throws SQLException {
|
||||
final var connection = dataSource.getConnection();
|
||||
final var statement = connection.prepareStatement("SELECT * FROM patients WHERE id = ?");
|
||||
statement.setString(1, patientId);
|
||||
final var rs = statement.executeQuery();
|
||||
if (!rs.next()) {
|
||||
throw new IllegalArgumentException("Patient with id " + patientId + " does not exist");
|
||||
}
|
||||
}
|
||||
|
||||
private String saveToRecordsSystem(final InputStream is) throws IOException {
|
||||
final var id = UUID.randomUUID().toString();
|
||||
final var path = recordsDir.resolve("record-" + id + ".json");
|
||||
Files.copy(is, path);
|
||||
final var connection = dataSource.getConnection();
|
||||
final PreparedStatement statement = connection.prepareStatement("INSERT INTO records (path) VALUES ?");
|
||||
statement.setString(1, path.toString());
|
||||
statement.executeUpdate();
|
||||
return id;
|
||||
return path.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue