Reputation: 420
In my spring boot service, I'm using https://github.com/java-json-tools/json-patch for handling PATCH requests.
Everything seems to be ok except a way to avoid modifying immutable fields like object id's, creation_time etc. I have found a similar question on Github https://github.com/java-json-tools/json-patch/issues/21 for which I could not find the right example.
This blog seems to give some interesting solutions about validating JSON patch requests with a solution in node.js. Would be good to know if something similar in JAVA is already there.
Upvotes: 13
Views: 4128
Reputation: 179
In Spring (but not only in Spring) you can use JSONObject helper class (provided by spring) together with ObjectMapper and check if patch contains element using a has method from JSONObject class like this:
var jsonObject = new JSONObject(objectMapper.writeValueAsString(patch));
if (jsonObject.has("property")) {
// do logic here
}
In this case you can do it for any element in json patch or merge patch no matter of element type. This solution will work not only for Spring. There are other vendors which provides JSONObject class which will do the same (org.json, etc.). And convert json patch to string is also possible with different library.
Upvotes: 0
Reputation: 1277
Another solution would be to imperatively deserialize and validate the request body.
So your example DTO might look like this:
public class CatDto {
@NotBlank
private String name;
@Min(0)
@Max(100)
private int laziness;
@Max(3)
private int purringVolume;
}
And your controller can be something like this:
@RestController
@RequestMapping("/api/cats")
@io.swagger.v3.oas.annotations.parameters.RequestBody(
content = @Content(schema = @Schema(implementation = CatDto.class)))
// ^^ this passes your CatDto model to swagger (you must use springdoc to get it to work!)
public class CatController {
@Autowired
SmartValidator validator; // we'll use this to validate our request
@PatchMapping(path = "/{id}", consumes = "application/json")
public ResponseEntity<String> updateCat(
@PathVariable String id,
@RequestBody Map<String, Object> body
// ^^ no Valid annotation, no declarative DTO binding here!
) throws MethodArgumentNotValidException {
CatDto catDto = new CatDto();
WebDataBinder binder = new WebDataBinder(catDto);
BindingResult bindingResult = binder.getBindingResult();
binder.bind(new MutablePropertyValues(body));
// ^^ imperatively bind to DTO
body.forEach((k, v) -> validator.validateValue(CatDto.class, k, v, bindingResult));
// ^^ imperatively validate user input
if (bindingResult.hasErrors()) {
throw new MethodArgumentNotValidException(null, bindingResult);
// ^^ this can be handled by your regular exception handler
}
// Here you can do normal stuff with your cat DTO.
// Map it to cat model, send to cat service, whatever.
return ResponseEntity.ok("cat updated");
}
}
No need for Optional's, no extra dependencies, your normal validation just works, your swagger looks good. The only problem is, you don't get proper merge patch on nested objects, but in many use cases that's not even required.
Upvotes: 1
Reputation: 717
Instead of receiving a JsonPatch
directly from the client, define a DTO to handle the validation and then you will later convert the DTO instance to a JsonPatch
.
Say you want to update a user of instance User.class
, you can define a DTO such as:
public class UserDTO {
@Email(message = "The provided email is invalid")
private String username;
@Size(min = 2, max = 10, message = "firstname should have at least 2 and a maximum of 10 characters")
private String firstName;
@Size(min = 2, max = 10, message = "firstname should have at least 2 and a maximum of 10 characters")
private String lastName;
@Override
public String toString() {
return new Gson().toJson(this);
}
//getters and setters
}
The custom toString
method ensures that fields that are not included in the update request are not prefilled with null
values.
Your PATCH
request can be as follows(For simplicity, I didn't cater for Exceptions)
@PatchMapping("/{id}")
ResponseEntity<Object> updateUser(@RequestBody @Valid UserDTO request,
@PathVariable String id) throws ParseException, IOException, JsonPatchException {
User oldUser = userRepository.findById(id);
String detailsToUpdate = request.toString();
User newUser = applyPatchToUser(detailsToUpdate, oldUser);
userRepository.save(newUser);
return userService.updateUser(request, id);
}
The following method returns the patched User which is updated above in the controller.
private User applyPatchToUser(String detailsToUpdate, User oldUser) throws IOException, JsonPatchException {
ObjectMapper objectMapper = new ObjectMapper();
// Parse the patch to JsonNode
JsonNode patchNode = objectMapper.readTree(detailsToUpdate);
// Create the patch
JsonMergePatch patch = JsonMergePatch.fromJson(patchNode);
// Convert the original object to JsonNode
JsonNode originalObjNode = objectMapper.valueToTree(oldUser);
// Apply the patch
TreeNode patchedObjNode = patch.apply(originalObjNode);
// Convert the patched node to an updated obj
return objectMapper.treeToValue(patchedObjNode, User.class);
}
Upvotes: 1
Reputation: 6331
Under many circumstances you can just patch an intermediate object which only has fields that the user can write to. After that you could quite easily map the intermediate object to your entity, using some object mapper or just manually.
The downside of this is that if you have a requirement that fields must be explicitly nullable, you won’t know if the patch object set a field to null explicitly or if it was never present in the patch.
What you can do too is abuse Optionals for this, e.g.
public class ProjectPatchDTO {
private Optional<@NotBlank String> name;
private Optional<String> description;
}
Although Optionals were not intended to be used like this, it's the most straightforward way to implement patch operations while maintaining a typed input. When the optional field is null, it was never passed from the client. When the optional is not present, that means the client has set the value to null.
Upvotes: 10