Skip to content

Commit

Permalink
Merge pull request ghidoz#224 from hpawe01/fix/support-relationship-r…
Browse files Browse the repository at this point in the history
…emoval

Allow removal of HasMany relations by setting empty array
  • Loading branch information
safo6m authored Jul 24, 2019
2 parents f549c1a + 8deadcc commit c953197
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/services/json-api-datastore.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -660,5 +660,27 @@ describe('JsonApiDatastore', () => {
}
});
});

it('should remove empty ToMany-relationships', () => {
const expectedUrl = `${BASE_URL}/${API_VERSION}/authors/${AUTHOR_ID}`;
const BOOK_NUMBER = 2;
const DATA = getAuthorData('books', BOOK_NUMBER);
const author = new Author(datastore, DATA);

author.books = [];

author.save().subscribe();

httpMock.expectNone(`${BASE_URL}/${API_VERSION}/authors`);
const saveRequest = httpMock.expectOne({ method: 'PATCH', url: expectedUrl });
const obj = saveRequest.request.body.data;
expect(obj.relationships).toBeDefined();
expect(obj.relationships.books).toBeDefined();
expect(obj.relationships.books.data).toBeDefined();
expect(obj.relationships.books.data.length).toBe(0);

saveRequest.flush({});

});
});
});
5 changes: 4 additions & 1 deletion src/services/json-api-datastore.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ export class JsonApiDatastore {
data: this.buildSingleRelationshipData(data[key])
};
}
} else if (data[key] instanceof Array && data[key].length > 0) {
} else if (data[key] instanceof Array) {
const entity = hasManyMetadata.find((entity: any) => entity.propertyName === key);
if (entity && this.isValidToManyRelation(data[key])) {
relationships = relationships || {};
Expand All @@ -254,6 +254,9 @@ export class JsonApiDatastore {
}

protected isValidToManyRelation(objects: Array<any>): boolean {
if (!objects.length) {
return true;
}
const isJsonApiModel = objects.every((item) => item instanceof JsonApiModel);
if (!isJsonApiModel) {
return false;
Expand Down

0 comments on commit c953197

Please sign in to comment.