Skip to content

Commit b3e0bd9

Browse files
authored
Merge pull request #234 from ghidoz/fix-parsing-has-many-relationship
Fix parsing has many relationships
2 parents 0af1cf8 + 13729af commit b3e0bd9

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

src/models/json-api.model.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,18 @@ describe('JsonApiModel', () => {
129129
});
130130
});
131131

132+
it('should return an empty array for hasMany relationship when one is included without any elements', () => {
133+
const BOOK_NUMBER = 0;
134+
const DATA = getAuthorData('books', BOOK_NUMBER);
135+
author = new Author(datastore, DATA);
136+
author.syncRelationships(DATA, getIncludedBooks(BOOK_NUMBER));
137+
138+
expect(author).toBeDefined();
139+
expect(author.id).toBe(AUTHOR_ID);
140+
expect(author.books).toBeDefined();
141+
expect(author.books.length).toBe(BOOK_NUMBER);
142+
});
143+
132144
it('should parse infinite levels of relationships by reference', () => {
133145
const BOOK_NUMBER = 4;
134146
const DATA = getAuthorData('books', BOOK_NUMBER);

src/models/json-api.model.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ export class JsonApiModel {
120120
for (const metadata of hasMany) {
121121
const relationship: any = data.relationships ? data.relationships[metadata.relationship] : null;
122122

123-
if (relationship && relationship.data && relationship.data.length > 0) {
123+
if (relationship && relationship.data && Array.isArray(relationship.data)) {
124124
let allModels: JsonApiModel[] = [];
125125
const modelTypesFetched: any = [];
126126

@@ -148,11 +148,9 @@ export class JsonApiModel {
148148
throw { message: `parseHasMany - Model type for relationship ${typeName} not found.` };
149149
}
150150
}
151-
152-
if (allModels.length > 0) {
153-
this[metadata.propertyName] = allModels;
154-
}
155151
}
152+
153+
this[metadata.propertyName] = allModels;
156154
}
157155
}
158156
}

0 commit comments

Comments
 (0)