infinum / Japx

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

Empty relationships are sent as Attributes, not Relationships #37

Closed cmillani closed 3 years ago

cmillani commented 4 years ago

Expected Behavior

While parsing, for example, the following structure:

struct Like: JapxCodable { var id: String var type: String = "likes" }

struct Article: JapxCodable { var id: String var type: String = "articles" var name: String var likes: [Like] }

Using

let notLikedArticle = Article(id: "1", name: "My Article", likes: []) let params = try! JapxEncoder().encode(notLikedArticle)

I expected the relationships key to have an empty likes value:

["data": ["relationships": ["likes": ["data": [[]]]], "attributes": ["name": My Article], "id": 1, "type": articles]]

Actual Behavior

The likes is encoded in the attributes key instead:

["data": ["id": 1, "attributes": ["name": My Article, "likes": []], "relationships": [:], "type": articles]]

Steps to Reproduce the Problem

  1. Define the structures Article and Like described above
  2. Encode an article with empty array of likes.

Specifications

I tried searching for options ou another way to configure that, but could not find any. Updating the Japx to 3.0 requires me to change the minimum target of the project, and I cannot do that now.

Any help is welcome :) Thanks!

cmillani commented 4 years ago

Is there any update to this issue or any known workaround I could use for this scenario?

@Truba @fgulan, I saw your names on the Readme, could you please give me a little help on this issue? :) Sorry if you are not the ones I should be mentioning here, if there is someone else to talk to please let me know.

Truba commented 4 years ago

Hi @cmillani , I'm sry I I'm just now seeing this issue.

This is a very interesting issue you are having here, which we haven't predicted. JapxCodable is just a shorthand to force user to add type and id to the object. Japx actually works on dictionary level by converting regular json dictionary to json:api dictionary. And on dictionary level empty attributes array is indistinguishable from empty relationship array.

We will need to add something like a decoding include list, but for encoding to give the user the option to explicitly distinguish attributes from relationships.

I'll try to create an update when I find some free time. p.s. PR's are always welcome if possible 😊

cmillani commented 4 years ago

Hey @Truba no problem! :)

I took a look on how encoding was done and saw exactly that, I was thinking of ways to implement that with little impact on what already works.

I'll try and think about how to do it and if I come up if something I'll open a PR! :)

Dundo7 commented 3 years ago

Hello, PR which is a possible fix for this has been merged to master. We will do a release this week. If the issue is still not resolved, feel free to re-open the issue.