Skip to content

Commit dccd572

Browse files
committed
Fix #17: Add id and localKey on relations associations
1 parent ee53739 commit dccd572

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

.gitignore

+3-1
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,6 @@ coverage
1818
node_modules
1919
npm-debug.log
2020
.vscode
21-
coverage
21+
coverage
22+
dist
23+
!dist/js-data-jsonapi-light.*

src/deserializer.ts

+10
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,18 @@ export function jsonApiDeserialize(mapper:Mapper, res:any, opts:any){
7070
continue;
7171
}
7272

73+
// In any case we include the Id in the attributes if we are in the
74+
// case of a `belongsTo`
75+
// For `hasOne`, like it's the remote object which should include
76+
// the key, we don't do anything.
77+
if (relation.type === 'belongsTo') {
78+
item.attributes[relation.localKey] = link.id;
79+
}
80+
7381
if (itemsIndexed[link.type] && itemsIndexed[link.type][link.id]) {
82+
let remoteIdAttribute = relation.relatedCollection.idAttribute;
7483
let itemLinked:any = itemsIndexed[link.type][link.id];
84+
itemLinked.attributes[remoteIdAttribute] = link.id;
7585
item.attributes[relation.localField] = itemLinked.attributes;
7686
}
7787
} else if (relation.type === 'hasMany') {

test/api/articles.json

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"links": {
3+
"self": "api/articles.json"
4+
},
5+
"data": [
6+
{
7+
"type": "Article",
8+
"id": "017bc4b9-014c-4873-bbda-12c4f5475740",
9+
"attributes": {
10+
"title": "What's up today?",
11+
"content": "Nothing much..."
12+
},
13+
"relationships": {
14+
"author": {
15+
"links": {
16+
"related": "api/articles/017bc4b9-014c-4873-bbda-12c4f5475740/authors.json"
17+
},
18+
"data": {
19+
"id": "e81fea3d-6379-4137-8068-7d70a90a1a7c",
20+
"type": "User"
21+
}
22+
}
23+
},
24+
"links": {
25+
"self": "api/articles/017bc4b9-014c-4873-bbda-12c4f5475740.json"
26+
}
27+
}
28+
]
29+
}

0 commit comments

Comments
 (0)