Add JSON response handling for form activity check

Refactor `FormActiveController` to return JSON responses using `BooleanResponse`. Introduce exception handling for JSON processing errors and update `FormActiveData` to allow object initialization without parameters.
This commit is contained in:
2024-08-10 03:10:02 +02:00
parent a9d4377599
commit 1a5be5021b
5 changed files with 143 additions and 59 deletions
@@ -0,0 +1,4 @@
package com.alttd.forms.controlers.form_active;
public record BooleanResponse(boolean isActive) {
}
@@ -1,7 +1,8 @@
package com.alttd.forms.controlers.form_active;
import com.alttd.forms.form.FormSettingsQuery;
import jakarta.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -21,7 +22,7 @@ public class FormActiveController {
private static final Logger logger = LoggerFactory.getLogger(FormActiveController.class);
@PostMapping("/formActive")
public CompletableFuture<ResponseEntity<String>> formActiveRequest(@Valid @RequestBody FormActiveData formData, HttpServletRequest request) {
public CompletableFuture<ResponseEntity<String>> formActiveRequest(@Valid @RequestBody FormActiveData formData) {
logger.debug("formActive");
logger.trace(formData.toString());
@@ -29,12 +30,17 @@ public class FormActiveController {
return formSettingsQuery
.isActive(formData.formName)
.thenApply(result -> {
if (result.isEmpty()) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to check if the form is active");
} else if (result.get()) {
return ResponseEntity.ok("yes");
} else {
return ResponseEntity.ok("no");
try {
if (result.isEmpty()) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to check if the form is active");
} else if (result.get()) {
return ResponseEntity.ok(new ObjectMapper().writeValueAsString(new BooleanResponse(true)));
} else {
return ResponseEntity.ok(new ObjectMapper().writeValueAsString(new BooleanResponse(false)));
}
} catch (JsonProcessingException e) {
logger.error("Failed to parse BooleanResponse", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to respond");
}
});
}
@@ -6,6 +6,8 @@ import org.hibernate.validator.constraints.Length;
public class FormActiveData {
public FormActiveData() {}
public FormActiveData(String formName) {
this.formName = formName;
}
@@ -13,6 +15,6 @@ public class FormActiveData {
@NotEmpty(message = "You have to provide a form name")
@Length(min = 1, max = 64, message = "Usernames have to be between 3 and 16 characters")
@Pattern(regexp = "[a-zA-Z]{1,64}", message = "This is an invalid form name")
public final String formName;
public String formName;
}