NestJs权限管理系统四、部门Department模块功能开发

116 阅读2分钟

DTO 是一个用于传输数据的对象,通常用于在客户端和服务器之间传输数据。在 NestJs 中,我们可以使用 DTO 来定义请求和响应的数据结构,以及进行数据验证和转换。通常情况下,我们会将 DTO 文件放在一个单独的目录中,以便于管理和维护,并配合@nestjs/swaggerclass-validator

部门模块

先罗列部门模块需要的功能:

  • 查询部门列表

  • 查询单个部门

  • 新增部门

  • 更新部门

  • 删除部门

  • 移动排序

  • 查询部门下的子部门数量

  • 和角色关联的功能(写到 role 模块的时候再实现)

    • 根据角色查询对应部门列表(使用角色部门关联表)
    • 部门下的角色数量

新增 src/modules/admin/system/department/departement.dto.ts

import { ApiProperty } from '@nestjs/swagger';
import { IsInt, IsOptional, IsString, Min, MinLength } from 'class-validator';

export class CreateDeptDto {
  @ApiProperty({ description: '部门名称' })
  @IsString()
  @MinLength(1)
  name: string;

  @ApiProperty({ description: '父级部门id', required: false })
  @IsInt()
  parentId: number;

  @ApiProperty({ description: '排序编号', required: false })
  @IsOptional()
  @IsInt()
  @Min(0)
  orderNum: number;
}

新建 service 服务类, 执行 nest g service modules/admin/system/department 后会自动将 DepartmentService 注入到 system.module.ts中的providers中。

import { Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import SysDepartment from '@/entities/admin/sys-department.entity';

@Injectable()
export class DepartmentService {
  constructor(
    @InjectRepository(SysDepartment)
    private departmentRepository: Repository<SysDepartment>,
  ) {}

  /**
   * 新增部门
   * @param name
   * @param parentId
   */
  async add(name: string, parentId: number): Promise<void> {
    await this.departmentRepository.insert({
      name,
      parentId: parentId === -1 ? null : parentId,
    });
  }
}

创建一个controller控制器来做一个请求,看是否响应成功。

执行命令: nest g co modules/admin/system/department

nest自动将 DepartmentController 类注入到 system.module.ts 中的 controllers中。

department.controller.ts

import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateDeptDto } from './department.dto';
import { DepartmentService } from './department.service';

@ApiTags('部门模块')
@Controller('department')
export class DepartmentController {
  constructor(private deptService: DepartmentService) {}

  @ApiOperation({ summary: '新增部门' })
  @Post('add')
  async add(@Body() dto: CreateDeptDto): Promise<void> {
    await this.deptService.add(dto.name, dto.parentId);
  }
}

我们在开发完add服务后可以在浏览器访问: localhost:8000/swagger-api 去做自测。

部门模块

其他功能可以按照功能列表或具体的业务需求去逐一实现,这里不再做详细代码说明,具体代码可以访问这里