Cannot read attributes of `null`
seberik opened this issue · 5 comments
When I run deserialize on { data: null }
i get the following error: cannot read attributes of null
but it is an valid json-api response. Is this expected behavior?
I don't believe { data: null }
is a valid response.
https://jsonapi.org/format/#document-top-level
`data`: the document’s “primary data”
Primary data MUST be either:
- a single resource object, a single resource identifier object, or null, for requests that target single resources
- an array of resource objects, an array of resource identifier objects, or an empty array ([]), for requests that target resource collections
So it should be either single resource
{
"data": {
"type": "articles",
"id": "1",
"attributes": {
// ... this article's attributes
}
}
or array (empty or with resources)
{
data: []
}
Having the same issue.
@aalimovs is it possible you missed the "or null"? Or are you interpreting it differently?
data MUST be either: a single resource object (1), a single resource identifier object (2), or null (3) for ... single resources
It feels like every time I read the spec I find another way I've misunderstood it 😛
@davidgovea good catch 😅 I missed that.
We do actually have data: null
ourselves, but only in has-one/belongs-to relationships. We normally 404 if you request something like /articles/999
where it doesn't exist.
Can you share a code example when you get that error?
Here's an example: https://codesandbox.io/s/jsonapi-deserializer-error-oie91
It's not ideal, but sometimes we have a need for data-less 200
success responses (especially when wrapping older restish apis with JSON:API) So, what is the "minimum" non-error JSON-API document? { meta: { } }
? Dummy "OK" data? We're, currently using data:null
, and patching the deserializer behavior in a catch {}
Here is my jsonapi-serializer+3.6.9.patch
to solve this
diff --git a/node_modules/jsonapi-serializer/lib/deserializer.js b/node_modules/jsonapi-serializer/lib/deserializer.js
index 1cb7c1a..d8fc6e4 100644
--- a/node_modules/jsonapi-serializer/lib/deserializer.js
+++ b/node_modules/jsonapi-serializer/lib/deserializer.js
@@ -31,8 +31,9 @@ module.exports = function (opts) {
return result
});
}
-
- if (Array.isArray(jsonapi.data)) {
+ if (!jsonapi.data) {
+ return jsonapi.data
+ } else if (Array.isArray(jsonapi.data)) {
return collection();
} else {
return resource();