fix: list trees (#1810)

* fix: list trees

* fix: test
This commit is contained in:
ChengLei Shao 2023-05-06 14:28:13 +08:00 committed by GitHub
parent b8c85c91b4
commit 258f4e980d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 80 additions and 0 deletions

View File

@ -52,6 +52,7 @@ export class AdjacencyListRepository extends Repository {
if (!nodeMap[`${node[foreignKey]}`]) {
nodeMap[`${node[foreignKey]}`] = [];
}
nodeMap[`${node[foreignKey]}`].push(node);
});
@ -90,8 +91,15 @@ export class AdjacencyListRepository extends Repository {
delete node[childrenKey];
}
} else {
// patch for sequelize toJSON
if (node._options.includeNames && !node._options.includeNames.includes(childrenKey)) {
node._options.includeNames.push(childrenKey);
}
node.setDataValue('__index', `${index}`);
children = node.getDataValue(childrenKey);
if (children.length === 0) {
node.setDataValue(childrenKey, undefined);
}

View File

@ -0,0 +1,72 @@
import { MockServer } from '@nocobase/test';
import { Database } from '@nocobase/database';
import { createApp } from '../index';
import lodash from 'lodash';
describe('tree', () => {
let app: MockServer;
let agent;
let db: Database;
beforeEach(async () => {
app = await createApp();
agent = app.agent();
db = app.db;
});
afterEach(async () => {
await app.destroy();
});
it('should list tree', async () => {
await db.getRepository('collections').create({
values: {
name: 'categories',
tree: 'adjacency-list',
fields: [
{ type: 'string', name: 'name' },
{
type: 'belongsTo',
name: 'parent',
foreignKey: 'parent_id',
treeParent: true,
target: 'categories',
},
{
type: 'hasMany',
name: 'children',
foreignKey: 'parent_id',
treeChildren: true,
target: 'categories',
},
],
},
context: {},
});
const c1 = await db.getRepository('categories').create({
values: { name: 'c1' },
});
await db.getRepository('categories').create({
values: [
{
name: 'c2',
parent: {
name: 'c1',
id: c1.get('id'),
},
},
],
});
const listResponse = await agent.resource('categories').list({
appends: ['parent'],
});
expect(listResponse.statusCode).toBe(200);
console.log(listResponse.body);
});
});