Skip to content

Commit

Permalink
fix: data with relationships and no attributes should be in included (#…
Browse files Browse the repository at this point in the history
…128)

closes #128
  • Loading branch information
danivek committed Sep 14, 2021
1 parent 138f6fc commit 631ce31
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/JSONAPISerializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -848,7 +848,10 @@ module.exports = class JSONAPISerializer {
const identifier = `${type}-${serializedRelationship.id}`;

// Not include relationship object which only contains an id
if (serializedIncluded.attributes && Object.keys(serializedIncluded.attributes).length) {
if (
(serializedIncluded.attributes && Object.keys(serializedIncluded.attributes).length) ||
(serializedIncluded.relationships && Object.keys(serializedIncluded.relationships).length)
) {
// Merge relationships data if already included
if (included.has(identifier)) {
const alreadyIncluded = included.get(identifier);
Expand Down
25 changes: 25 additions & 0 deletions test/unit/JSONAPISerializer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,31 @@ describe('JSONAPISerializer', function() {
done();
});

it('should return serialized relationship data and included for a relationship object with at least relationships', function(done) {
const serializer = new JSONAPISerializer();
serializer.register('authors', {
relationships: {
friends: {
type: 'people'
}
}
});
serializer.register('people');

const included = new Map();
const serializedRelationshipData = serializer.serializeRelationship('authors', 'default', {id: '1', friends: ['1', '2']}, included);
expect(serializedRelationshipData).to.have.property('type').to.eql('authors');
expect(serializedRelationshipData).to.have.property('id').to.eql('1');
const includedValue = [...included.values()];
expect(includedValue).to.have.lengthOf(1);
expect(includedValue[0]).to.have.property('type').to.eql('authors');
expect(includedValue[0]).to.have.property('id').to.eql('1');
expect(includedValue[0]).to.have.property('relationships').to.have.property('friends').to.have.property('data').to.have.lengthOf(2);
expect(includedValue[0].relationships.friends.data[0]).to.have.property('type').to.eql('people');
expect(includedValue[0].relationships.friends.data[0]).to.have.property('id').to.eql('1');
done();
});

it('should return serialized relationship data and populated included with a custom schema', function(done) {
const Serializer2 = new JSONAPISerializer();
// Custom schema 'only-name' for authors resource
Expand Down

0 comments on commit 631ce31

Please sign in to comment.