Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix expand hasMany relationship #1542

Open
wants to merge 1 commit into
base: v0
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions src/server/router/plural.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,16 @@ module.exports = (db, name, opts) => {
[].concat(e).forEach((innerResource) => {
const plural = pluralize(innerResource)
if (db.get(plural).value()) {
const prop = `${innerResource}${opts.foreignKeySuffix}`
resource[innerResource] = db
.get(plural)
.getById(resource[prop])
.value()
// Search for `<resourceName>` before `<resourceName>Id` key in the resource
// if `<resourceName>` not found, then look for `<resourceName>Id`
// we need this for hasMany relationship, e.g. `posts/3?_expand=tags`
// here will search first for `tags` key inside `resource` before looking for `tagsId`
const prop = Object.keys(resource).includes(innerResource) ? innerResource : `${innerResource}${opts.foreignKeySuffix}`;

// Now just check if its value is an array, e.g. `"tags": [1, 2]` or just `"userId": 3`
resource[innerResource] = (Array.isArray(resource[prop]))
? resource[prop].reduce((acc, id) => [...acc, db.get(plural).getById(id).value()], [])
: resource[innerResource] = db.get(plural).getById(resource[prop]).value();
}
})
}
Expand Down