json-api-serializer icon indicating copy to clipboard operation
json-api-serializer copied to clipboard

Having no attributes in the relation data does not add relation to included array

Open AmauryD opened this issue 2 years ago • 0 comments

When the relationship's value only have an id key in their structure, the relation is in "relationships" but not in the "included" array.

The serializer code (simplified)

const serializer = new JSONAPISerializer({

});
this.serializer.register('user', {
  whitelist: ['firstName', 'lastName'],
  relationships: {
    documents: {
      type: 'document',
    },
  },
});
this.serializer.register('document', {
  whitelist: ['filename', 'mimetype', 'originalName', 'path', 'size']
});

return this.serializer.serializeAsync(
    'user',
    { id: '12345678910abcdef', documents: [ { id: '123456789' } ] },
    extraData ?? ({} as any),
  );

The API response

{
	"jsonapi": {
		"version": "1.0"
	},
	"links": {
		"self": "/api/v1/users/12345678910abcdef"
	},
	"data": {
		"type": "user",
		"id": "12345678910abcdef",
		"relationships": {
			"documents": {
				"data": [
					{
						"type": "document",
						"id": "123456789"
					}
				]
			}
		},
		"links": {
			"self": "/api/v1/users/12345678910abcdef"
		}
	}
}

I think the correct output would be something like this :

{
	"jsonapi": {
		"version": "1.0"
	},
	"links": {
		"self": "/api/v1/users/12345678910abcdef"
	},
	"data": {
		"type": "user",
		"id": "12345678910abcdef",
		"relationships": {
			"documents": {
				"data": [
					{
						"type": "document",
						"id": "123456789"
					}
				]
			}
		},
		"links": {
			"self": "/api/v1/users/12345678910abcdef"
		}
	}
        "included": [
		        {
			        "type": "document",
			        "id": "123456789",
			        "attributes": {},
			        "links": {
				        "self": "/api/v1/documents/123456789"
			        }
		        }
	        ]
}

AmauryD avatar Apr 11 '22 13:04 AmauryD