From 8183ff55642340514b400d74d497a44486990329 Mon Sep 17 00:00:00 2001 From: ChengLei Shao Date: Tue, 9 May 2023 16:48:40 +0800 Subject: [PATCH] chore: should not return children property when child nodes are empty (#1825) --- .../core/database/src/__tests__/tree.test.ts | 57 +++++++++++++++++++ packages/core/database/src/repository.ts | 2 +- .../adjacency-list-repository.ts | 11 +++- 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/packages/core/database/src/__tests__/tree.test.ts b/packages/core/database/src/__tests__/tree.test.ts index 498c260ff..30ff7e013 100644 --- a/packages/core/database/src/__tests__/tree.test.ts +++ b/packages/core/database/src/__tests__/tree.test.ts @@ -16,6 +16,63 @@ describe('tree test', function () { await db.close(); }); + it('should not return children property when child nodes are empty', async () => { + const collection = db.collection({ + name: 'categories', + tree: 'adjacency-list', + fields: [ + { type: 'string', name: 'name' }, + { + type: 'belongsTo', + name: 'parent', + treeParent: true, + }, + { + type: 'hasMany', + name: 'children', + treeChildren: true, + }, + ], + }); + + await db.sync(); + + await collection.repository.create({ + values: [ + { + name: 'c1', + children: [ + { + name: 'c11', + }, + { + name: 'c12', + }, + ], + }, + { + name: 'c2', + }, + ], + }); + + const tree = await collection.repository.find({ + filter: { + parentId: null, + }, + }); + + const c2 = tree.find((item) => item.name === 'c2'); + expect(c2.toJSON()['children']).toBeUndefined(); + + const c11 = tree + .find((item) => item.name === 'c1') + .get('children') + .find((item) => item.name === 'c11'); + + expect(c11.toJSON()['children']).toBeUndefined(); + }); + it('should add sort field', async () => { const Tasks = db.collection({ name: 'tasks', diff --git a/packages/core/database/src/repository.ts b/packages/core/database/src/repository.ts index 7950894c8..3bdc13dc9 100644 --- a/packages/core/database/src/repository.ts +++ b/packages/core/database/src/repository.ts @@ -263,7 +263,7 @@ export class Repository { + async find(options: FindOptions & { addIndex?: boolean } = {}): Promise { const parentNodes = await super.find(lodash.omit(options)); if (options.raw) { @@ -80,7 +80,10 @@ export class AdjacencyListRepository extends Repository { } return children.map((child) => { - child.setDataValue(childrenKey, buildTree(child.id)); + const childrenValues = buildTree(child.id); + if (childrenValues.length > 0) { + child.setDataValue(childrenKey, childrenValues); + } return child; }); } @@ -88,7 +91,9 @@ export class AdjacencyListRepository extends Repository { for (const parent of parentNodes) { const parentId = parent[primaryKey]; const children = buildTree(parentId); - parent.setDataValue(childrenKey, children); + if (children.length > 0) { + parent.setDataValue(childrenKey, children); + } } this.addIndex(parentNodes, childrenKey, options);