12

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.

shoaib1992
  • 410
  • 1
  • 8
  • 26

3 Answers3

10

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.

Sebastiaan van den Broek
  • 5,818
  • 7
  • 40
  • 73
1

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);
    }
Enock Lubowa
  • 679
  • 8
  • 12
  • Your "toString" cannot distinguish between null and not provided values, which is the whole point of patch. See https://stackoverflow.com/questions/38424383/how-to-distinguish-between-null-and-not-provided-values-for-partial-updates-in-s – Flyout91 May 10 '22 at 11:55
1

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.

Michał Jabłoński
  • 1,129
  • 1
  • 13
  • 15
  • This indeed looks interesting if you don't need nested objects, but how would it improve swagger compared to at least a somewhat typed input object? The input is just a map of object here. – Sebastiaan van den Broek Dec 12 '22 at 01:23
  • @SebastiaanvandenBroek, great point! You need springdoc and an extra annotation to get the good looking swagger here. See my updated answer. – Michał Jabłoński Dec 12 '22 at 19:02
  • Ahh yeah, fair enough, although that would work with any kind of solution but it's still nice to be able to override it if using Swagger. The main issue I have with this is that you still cannot actually treat the CatDTO the same way in the service as if you had received the complete object initially. Because if for example there's some field `name` that is null in the CatDTO, you still don't know if they intended to set that field to null or if they never passed a value for it. So for updating the db based on this, you simply don't have sufficient information (if things are nullable) – Sebastiaan van den Broek Dec 13 '22 at 06:34
  • @SebastiaanvandenBroek, well that might be the case if you're passing Dto's to services (which I personally try to avoid). In that case you might need to overload some methods in your services to accept for example an array of `updateProperties`, which you can construct from keys of your `Map body`. – Michał Jabłoński Dec 13 '22 at 10:22
  • Yeah, although the Optional 'hack' I used does that too while maintaining type safety and not having to make a manual mapping between key strings and object fields. I still think that's the easier solution if you need nullability of fields. This is very useful when you don't though. – Sebastiaan van den Broek Dec 13 '22 at 10:34
  • Haha, honestly I like your Optional's abuse more than my solution. I wrote my solution because people on my team would never approve Optional's ("they were not intended for this kind of usage" etc.). – Michał Jabłoński Dec 13 '22 at 10:40
  • Yeah it's not too pretty, but it's harder to introduce bugs with typed fields. Although we're soon going to refactor it all anyway since we do need nested partial objects too. Although technically that's still possible with optional objects too, but all the checking becomes cumbersome. I'm a bit surprised there's no built-in support for this with some form of type safety though. Like some tuple where the boolean indicates if the field has been set, and validation is only triggered if so. – Sebastiaan van den Broek Dec 13 '22 at 11:41
  • O... In general, patch requests are surprisingly hard to implement correctly, with nullability, validation and swagger support, not to mention nested objects. Tried it with C# and it's not easy there too. Wondering what other people do to update objects? Get and put on client side? Patch without nullability and validation? – Michał Jabłoński Dec 13 '22 at 12:20