json-server icon indicating copy to clipboard operation
json-server copied to clipboard

Fix `expand` hasMany relationship

Open flashios09 opened this issue 1 year ago • 0 comments

The _expand query param would work with a belongsTo relationship but not with hasMany relationship.

For this db.json:

{
  "posts": [{
     "id": 1,
     "title": "My post title",
     "userId": 2,
     "tags": [1, 2]
  }],
  "users": [...],
  "tags": [...]
}

This posts/3?_expand=user work since the post has a userId foreign key as "userId" : 2, it's just a belongsTo relationship, but posts/3?_expand=tags will not work since it will look for tagsId property inside the post, and deal with the value as a number not number[], so expect "tagsId": n not "tagsId": [x, y, z].

Updating the expand function fixes this issue, now it will check first if the key exists in the resource, so check first for "tags" before tagsId, means before adding the Id suffix:

 const prop = Object.keys(resource).includes(innerResource) 
   ? innerResource 
   : `${innerResource}${opts.foreignKeySuffix}`;

Then check if its value is an array, e.g. "tags": [1, 2]

resource[innerResource] = (Array.isArray(resource[prop]))
  // `"tags": [1, 2]`
  ? resource[prop].reduce((acc, id) => [...acc, db.get(plural).getById(id).value()], [])
  // `"userId": 2`
  : resource[innerResource] = db.get(plural).getById(resource[prop]).value();

flashios09 avatar Apr 28 '24 08:04 flashios09