Skip to content

Commit

Permalink
Merge pull request #177 from Embraser01/handle-nested-populate
Browse files Browse the repository at this point in the history
Handle nested field populate
  • Loading branch information
icebob authored Apr 14, 2020
2 parents ac812fc + 0cc0c82 commit c2f9d43
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
2 changes: 1 addition & 1 deletion packages/moleculer-db/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions packages/moleculer-db/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -619,16 +619,16 @@ module.exports = {
let arr = Array.isArray(docs) ? docs : [docs];

// Collect IDs from field of docs (flatten, compact & unique list)
let idList = _.uniq(_.flattenDeep(_.compact(arr.map(doc => doc[field]))));
let idList = _.uniq(_.flattenDeep(_.compact(arr.map(doc => _.get(doc, field)))));
// Replace the received models according to IDs in the original docs
const resultTransform = (populatedDocs) => {
arr.forEach(doc => {
let id = doc[field];
let id = _.get(doc, field);
if (_.isArray(id)) {
let models = _.compact(id.map(id => populatedDocs[id]));
doc[field] = models;
_.set(doc, field, models);
} else {
doc[field] = populatedDocs[id];
_.set(doc, field, populatedDocs[id]);
}
});
};
Expand Down
27 changes: 27 additions & 0 deletions packages/moleculer-db/test/unit/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,7 @@ describe("Test populateDocs method", () => {
adapter: mockAdapter,
settings: {
populates: {
"likes.users": "users.get",
"comments": "comments.get",
"author": {
action: "users.get",
Expand Down Expand Up @@ -826,6 +827,32 @@ describe("Test populateDocs method", () => {
}).catch(protectReject);
});

it("should call 'populateDocs' with single doc & only likes.users population", () => {
const ctx = { params: {} };
ctx.call = jest.fn(() => Promise.resolve({
"3": {
"name": "Walter"
},
"5": {
"name": "John"
},
"8": {
"name": "Jane"
}
}));
const doc = { id: 4, likes: { users: [8, 3], shared: 4 } };

return service.populateDocs(ctx, doc, ["likes.users"]).then(res => {
expect(res).toEqual({
id: 4,
likes: {
users: [{ name: "Jane" }, { name: "Walter" }],
shared: 4,
},
});
}).catch(protectReject);
});

it("should return docs if no populate list", () => {
const docs = [];
const ctx = { params: {} };
Expand Down

0 comments on commit c2f9d43

Please sign in to comment.