typicode / json-server

Get a full fake REST API with zero coding in less than 30 seconds (seriously)
Other
72.67k stars 7.01k forks source link

Fix `expand` hasMany relationship #1542

Open flashios09 opened 5 months ago

flashios09 commented 5 months ago

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();