infinum / Japx

Lightweight parser for the complex JSON:API (http://jsonapi.org/) structure.
MIT License
152 stars 35 forks source link

Encoding object with nested included objects #28

Closed EmirBostanci closed 4 years ago

EmirBostanci commented 5 years ago

Expected Behavior

There should be a documentation about encoding nested included objects.

Actual Behavior

Currently, nor on example project neither documentation, there is no info about this topic.

Steps to Reproduce the Problem

  1. can you plase add documentation or example.

Specifications

Truba commented 4 years ago

Hi, @EmirBostanci According to the official JSON:API documentation you can't encode included objects. You only encode relationships in your top object / objects.

What Japx is doing is simply taking the type and id pairs from your "sub-object" and putting them in your "main object" as relationships. i.e. From:

{
    "id": "id",
    "type": "user",
    "subObject": {
        "id": "id",
        "type": "post",
        "title": "Some title"
    }
}

to

{
    "data": {
        "id": "id",
        "type": "user",
        "relationships": {
            "subObject": {
                "data": { "id": "id", "type": "post" }
            }
        }
    }
}

For updating or creating "sub-objects" you should firstly update or create them, get the id's if it was a create operation, and then update the "main object" with those ids.

I've also seen people create additional nested objects with the same values as the relationship and then handling that on client and server. It looks something like this:

{
    "id": "id",
    "type": "user",
    "subObjectForUpdate": {
        "title": "Some title"
    }
}

to be used as

{
    "data": {
        "id": "id",
        "type": "user",
        "subObjectForUpdate": {
            "title": "Some title"
        }
    }
}

While this is allowed under the JSON:API specification, it is mostly just a hack to compensate, since this feature is still missing from the JSON:API.

With all this sead, I realised that we really don't have a lot written about encoding in general in our README. For this I'm assigning this issue @fgulan , creator of README-s :)

@EmirBostanci For now if you want to see encoding in practice, you can take a look at Example project and Encoding tests that were created.

Truba commented 4 years ago

We added some real examples for issue #29 Hopefully that should be enough. Closing this issue for now. Please feel free to reopen if you feel the need.