实体表
import { Base } from '@/entities/base';
import { Entity, Column } from 'typeorm';
@Entity("user_department")
export class UserDepartment extends Base {
@Column({ comment: '部门 id', type: "int" }) pid: number
@Column({ comment: '部门中文名', type: "varchar" }) name: string
@Column({ comment: '部门英文名', type: "varchar" }) egname: string
}
配置路由请求数据
Nestjs 提供了其他 HTTP 请求方法的装饰器 @Get()、 @Post()、 @Put() 、 @Delete()、 @Patch()、 @Options()、 @Head() 和 @All()
在 user.controller.ts 文件中配置路由,代码如下:
import {
Controller,
Get,
Post,
Delete,
Body,
Query,
Put,
Param
} from '@nestjs/common';
import { UserService } from './user.service';
import { UserLoginDTO } from './dto/user-login.dto';
import { InfoModel,DepartmentTreeModel, EmployeeModel } from './model/user-model';
import { UserPwdDTO } from './dto/user-pwd.dto';
import { UserPasswordDTO } from './dto/user-password.dto';
import { UserCodeDTO } from './dto/user-code.dto';
import { UserForgetDTO } from './dto/user-forget.dto';
import { UserEmployeeDTO } from './dto/user-employee.dto';
@Controller('user')
export class UserController {
constructor(
private readonly userService: UserService) { }
// 获取部门树
@Get('/departmentTree')
getDepartmentTree(@Query() query:any): Promise<DepartmentTreeModel[]> {
return this.userService.getDepartmentTree(query.email);
}
}
定义数据模型
在 user.model.ts 文件中,定义数据模型
import { User } from '@/entities/user.entity';
export class DepartmentTreeModel {
// 父节点id
pid: number
// 主键id
id: number
// 中文名
name: string
// 英文名
egname: string
// 子部门
children: DepartmentTreeModel[]
}
查询代码实现
在 user.service.ts 文件中,编写实现方法
@Injectable()
export class UserService {
// private readonly users: Array<User>;
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
@InjectRepository(UserDepartment)
private readonly departmentRepository: Repository<UserDepartment>,
private readonly emailService: EmailService,
@InjectRedis() private readonly redis: Redis
) { }
// 获取部门树
async getDepartmentTree(email: string): Promise<DepartmentTreeModel[]> {
// 获取部门数据
let departments = await this.departmentRepository.createQueryBuilder().getMany();
// console.log(departments, '000');
// 获取用户信息
let userInfo = await this.findUserForEmail(email);
if (userInfo) {
return this.buildTree(departments, 0);
}
}
// 构造部门树
private buildTree(department: any, pid: number): DepartmentTreeModel[] {
let result: DepartmentTreeModel[] = [];
department.forEach((menu: any) => {
const departmentTree: DepartmentTreeModel = new DepartmentTreeModel();
departmentTree.pid = menu.pid;
departmentTree.id = menu.id;
departmentTree.name = menu.name;
departmentTree.egname = menu.egname;
if (menu.pid === pid) {
departmentTree.children = this.buildTree(department, menu.id);
result.push(departmentTree);
}
})
return result;
}
}
结果验证
在 ApiPost7 中模拟输出结果: