mattpolzin/JSONAPI

Problems using Include when parsing JSONAPI documents

SuperManifolds opened this issue · 3 comments

Hello, I am trying to use this library but I am running into problems with includes.
When trying to parse a document define like this:

typealias NicknameGetDocument = Document<SingleResourceBody<Nickname>, Include6<User, Rat, Group, Client, Epic, Ship>>

I get an errors like these

Fatal error: 'try!' expression unexpectedly raised an error: Include 1 failed to parse: 
Could not have been Include Type 1 because:
'rats' relationship should contain many values but found one

Could not have been Include Type 2 because:
found JSON:API type "users" but expected "rats"

Could not have been Include Type 3 because:
found JSON:API type "users" but expected "groups"

Could not have been Include Type 4 because:
found JSON:API type "users" but expected "clients"

Could not have been Include Type 5 because:
found JSON:API type "users" but expected "epics"

Could not have been Include Type 6 because:
found JSON:API type "users" but expected "ships": file

I cannot find much documentation on how the include works, I may be doing it wrong, I do not really understand what is expected here, if the includes must be defined in a specific order, what is that order?

Any help would be greatly appreciated.

You can disregard this question. This JSONAPI library actually uncovered an implementation error in our server.

Ah, very good. I had written the following response but GitHub did not allow me to post it earlier -- I will still post it now for others who might find it instructional.


I think I can deduce what is going on here.

Most of that error message is just saying something that would be fairly apparent when looking at the response data for the first included item: Its type is "users" so it cannot be parsed as "rats", "groups", "clients", etc.

The really key part of the error is that the first included item cannot be parsed as "users" because "'rats' relationship should contain many values but found one"

In hindsight this error has confusing wording, but what it means is that you've declared a relationship for your User type something like let rats: ToManyRelationship<Rat, ...> indicating the relationship must have the JSON:API form:

{
  "data": [
    { "id": ..., "type": "rats" },
    ...
  ]
}

When trying to parse the response you gave it, it actually encountered a to-one JSON:API relationship of the form:

{
  "data": { "id": ..., "type": "rats" }
}

Notice the structural difference of the "data" element being an array or not.

The response your server is giving would probably successfully parse as let rats: ToOneRelationship<Rat, ...>.

Yeah, I figured out our server has an implementation error where a many relationship with no elements would be null instead of empty array.
But thank you for the detailed response nonetheless :)