Relationships is null when not marked as included
Closed this issue · 1 comments
It seems that something is not working in my case, I explain to you:
My field city
(as relationship) doesn't not retrieve id
.
By default, without any lib, the result I have, is this:
{
"type": "news",
"id": "f0591a38-xxxx-42a6-xxxx-5eaddf178146",
"links": {},
"attributes": {},
"relationships": {
"node_type": {},
"uid": {},
"city": {
"data": {
"type": "cities",
"id": "9bdd1cc6-yyyy-4360-yyyy-22f2c766205e"
}
}
}
}
Now I've installed jsonapi-react
, and set this schema :
{
news: {
type: 'news',
fields: {
filter: {
status: 1,
},
},
relationships: {
city: {
type: 'cities',
},
},
},
city: {
type: 'cities',
fields: {
id: 'string',
},
},
}
When I use client.fetch('news')
or useQuery('news')
, the result contains city: null
:
{
"body": {},
"city": null,
"created": "2021-05-20T08:27:12+00:00",
"id": "192e952d-xxxx-408d-xxxx-32aa1e4d3579",
"langcode": "en",
"meta_tags": null,
"path": {},
"promote": false,
"sticky": false,
"title": "First News !"
}
IMO, it should at least retrieved city: { "id": "9bdd1cc6-yyyy-4360-yyyy-22f2c766205e" }
.
But I set include: ['city']
, the field city
is well filled :
{
"body": {},
"city": {
"created": "2021-05-20T08:26:59+00:00",
"id": "a7586583-aaaa-4420-aaaa-57a3ea885e85",
"initials": "AT",
"langcode": "en",
"meta_tags": null,
"path": {},
"promote": false,
"sticky": false,
"title": "Paris"
},
"created": "2021-05-20T08:27:12+00:00",
"id": "192e952d-xxxx-408d-xxxx-32aa1e4d3579",
"langcode": "en",
"meta_tags": null,
"path": {},
"promote": false,
"sticky": false,
"title": "First News !"
}
The question is : is there a way to return id
for my relationship city
without using include: ['city']
?
Thanks!
Hey @Steffi3rd,
The issue seems to be that your news
record contains a relationship with a data
hash, but the response does not have an included
field that contains the corresponding city
resource. When you use include: ['city']
it signals to your API that you want the associated city to also be returned, which in effect populates the included
field.
The way this library currently parses the response, is it goes through each item in the relationships
object that has a data
field, and then tries to find the accompanying record in the included
field (see here). If it's not found it assigns a value of null
.
I'm not sure off-hand if the response you shared is spec compliant, but I don't see a problem with assigning the data that is available, even if the resources wasn't included. You're welcome to submit a PR!