toedter / spring-hateoas-jsonapi

A JSON:API media type implementation for Spring HATEOAS
Apache License 2.0
106 stars 15 forks source link

Cannot set JSON:API field 'ID' on object of type #63

Closed atlas-tbrown closed 2 years ago

atlas-tbrown commented 2 years ago

Hi, This might be an issue with what im trying to do, but wanted to get some advice. We're trying the approach of possibly having different models for create, update, and get. For ex, if you use the same object for all of them, its hard to keep track of whats needed for say a create, whats valid to update, and whats always going to be returned, and so on.

So say we'd want a GET method that returns a Page

public class Page {
    public String id;
    public String title;
    public String status;
}

But then lets say for example on creation i only want title to be user provided. Some resources recommended having a different model for this:

public class CreatePage {
    @JsonApiType
    public String type = "pages";
    public String title;
}

So we'd have something like the above. Then in the controller we'd use as:

@RequestBody EntityModel<CreatePage> createPage

The issue becomes that since this is an entity model it seems to complain that it can't set the ID. But if i ADD the id field to this, it works, even if it doesnt actually set it. Would it be possible to somehow have it not error if the ID field isnt present? Is this pattern of doing separate models not really compatible with how this library works?

(Actually i see this also happens to cause an error if i have my usual model object, and expose just a getter for the id. It seems like in order to have the POST work i need to have some setter / way to set the ID even if it should never be called.)

Thanks!

toedter commented 2 years ago

I would not recomment to have different models, but just checking conditions in the respective controller methods instead. And yes, all JSON:API resources need an id. A HTTP POST with a JSON:API complient structure, but not having the id, would be fine though, e.g.

https://github.com/toedter/spring-hateoas-jsonapi/blob/08556b0ccf55c3c7f3f07220b708960f15b32878/example/src/test/java/com/toedter/spring/hateoas/jsonapi/example/JsonApiWebMvcIntegrationTest.java#L88-L116

For the use case that you want to serialze to JSON from an EntityModel without id, you could use a configuration option, see https://toedter.github.io/spring-hateoas-jsonapi/1.5.1/reference/#postWithNoId

Hope this helps.