角色增删改查

main
expressgy 3 months ago
parent 86498a5c94
commit 7488c21ed5
  1. 10
      src/application/auth-role/auth-role.controller.ts
  2. 377
      src/application/auth-role/auth-role.service.ts
  3. 2
      src/application/auth-role/dto/create-auth-role.dto.ts
  4. 3
      src/application/auth-role/dto/get-auth-role.dto.ts
  5. 25
      src/application/auth-role/dto/update-auth-role.dto.ts
  6. 59
      src/application/core-dict/core-dict.service.ts
  7. 2
      src/application/core-dict/dto/get-core-dict.dto.ts
  8. 17
      src/application/core-env/core-env.service.ts
  9. 7
      src/application/core-menu/core-menu.service.ts

@ -39,7 +39,7 @@ export class AuthRoleController {
@ApiProduces('application/json') @ApiProduces('application/json')
@Get(':id') @Get(':id')
findOne(@Param('id') id: string) { findOne(@Param('id') id: string) {
return this.authRoleService.findOne(+id); return this.authRoleService.findOne(id);
} }
@ApiOperation({ @ApiOperation({
@ -48,8 +48,8 @@ export class AuthRoleController {
}) })
@ApiProduces('application/json') @ApiProduces('application/json')
@Patch(':id') @Patch(':id')
update(@Param('id') id: string, @Body() updateAuthRoleDto: UpdateAuthRoleDto) { update(@Param('id') id: string, @Body() updateAuthRoleDto: UpdateAuthRoleDto, @PacInfo() pacInfo: PacInfoType) {
return this.authRoleService.update(+id, updateAuthRoleDto); return this.authRoleService.update(id, updateAuthRoleDto, pacInfo);
} }
@ApiOperation({ @ApiOperation({
summary: '删除目标角色', summary: '删除目标角色',
@ -57,7 +57,7 @@ export class AuthRoleController {
}) })
@ApiProduces('application/json') @ApiProduces('application/json')
@Delete(':id') @Delete(':id')
remove(@Param('id') id: string) { remove(@Param('id') id: string, @PacInfo() pacInfo: PacInfoType) {
return this.authRoleService.remove(+id); return this.authRoleService.remove(id, pacInfo);
} }
} }

@ -7,15 +7,36 @@ import { RedisService } from '@common/service/redis/redis.service';
import { Snowflake } from '@service/snowflake/snowflake.service'; import { Snowflake } from '@service/snowflake/snowflake.service';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { PacInfoType } from '@utils/myType'; import { PacInfoType } from '@utils/myType';
import { isTrueEnum } from '@utils/boolean.enum'; import { isExistKey, isTrueEnum } from '@utils/boolean.enum';
import { pacAuthLinkRoleDept, pacAuthLinkRoleMenu, pacAuthRole, pacAuthUser, pacCoreDict } from '@entities/schema'; import { pacAuthDept, pacAuthLinkRoleDept, pacAuthLinkRoleMenu, pacAuthRole, pacAuthUser, pacCoreDict, pacCoreMenu } from '@entities/schema';
import { and, eq, isNull, sql } from 'drizzle-orm'; import { and, asc, desc, eq, isNull, like, or, sql } from 'drizzle-orm';
import { GetPacAuthRoleAllDto } from '@app/auth-role/dto/get-auth-role.dto'; import { GetPacAuthRoleAllDto } from '@app/auth-role/dto/get-auth-role.dto';
import { likeQuery } from '@utils/likeQuery';
import { alias } from 'drizzle-orm/mysql-core';
@Injectable() @Injectable()
export class AuthRoleService { export class AuthRoleService {
// 基本分页信息 // 基本分页信息
private readonly roleBaseType = {}; private readonly rolePageType = {
roleId: pacAuthRole.roleId,
pid: pacAuthRole.pid,
roleName: pacAuthRole.roleName,
roleKey: pacAuthRole.roleKey,
roleDesc: pacAuthRole.roleDesc,
roleType: pacAuthRole.roleType,
roleTypeName: pacCoreDict.dictName,
roleTypeKey: pacCoreDict.dictKey,
deptScope: pacAuthRole.deptScope,
haveChildren: pacAuthRole.haveChildren,
root: pacAuthRole.root,
orderNum: pacAuthRole.orderNum,
status: pacAuthRole.status,
createby: pacAuthRole.createby,
createName: pacAuthUser.nickname,
createtime: pacAuthRole.createtime,
updateby: pacAuthRole.updateby,
updatetime: pacAuthRole.updatetime,
};
// 角色详细信息 // 角色详细信息
private readonly roleMoreType = { private readonly roleMoreType = {
@ -90,16 +111,18 @@ export class AuthRoleService {
}); });
// ! 增加关联菜单 // ! 增加关联菜单
await this.createMenuLink(newRoleResult.roleId, createAuthRoleDto.menuList, pacInfo.userId).catch((e) => { await this.createMenuLink(newRoleResult.roleId, createAuthRoleDto.menuList, pacInfo.userId as any).catch((e) => {
this.logger.error(e.message + e.track.toString()); this.logger.error(e.message + e.track.toString());
throw new HttpException('添加菜单关系出现错误,角色写入错误!', HttpStatus.INTERNAL_SERVER_ERROR); throw new HttpException('添加菜单关系出现错误,角色写入错误!', HttpStatus.INTERNAL_SERVER_ERROR);
}); });
// ! 增加关联部门 // ! 增加关联部门
await this.createDeptLink(newRoleResult.roleId, createAuthRoleDto.deptList, pacInfo.userId).catch((e) => { if (createAuthRoleDto.deptScope == 5) {
this.logger.error(e.message + e.track.toString()); await this.createDeptLink(newRoleResult.roleId, createAuthRoleDto.deptList, pacInfo.userId as any).catch((e) => {
throw new HttpException('添加部门数据范围关系出现错误,角色写入错误!', HttpStatus.INTERNAL_SERVER_ERROR); this.logger.error(e.message + e.track.toString());
}); throw new HttpException('添加部门数据范围关系出现错误,角色写入错误!', HttpStatus.INTERNAL_SERVER_ERROR);
});
}
// ! 解锁 // ! 解锁
lock(); lock();
@ -118,20 +141,95 @@ export class AuthRoleService {
} }
} }
findAll(getPacAuthRoleAllDto: GetPacAuthRoleAllDto) { /** Service
return `This action returns all authRole`; * NAME: findAll
* DESC: 获取角色信息列表/
* DATE: 2024-06-26 13:53:03 -
* */
public async findAll(getPacAuthRoleAllDto: GetPacAuthRoleAllDto) {
if (isTrueEnum(getPacAuthRoleAllDto['isList'])) {
return await this.getRoleList(getPacAuthRoleAllDto);
} else {
return await this.getRolePage(getPacAuthRoleAllDto);
}
} }
findOne(id: number) { /** Service
return `This action returns a #${id} authRole`; * NAME: findOne
* DESC: 获取角色详细信息
* DATE: 2024-06-26 16:15:21 -
* */
findOne(id: string) {
return this.getRoleMore(id);
} }
update(id: number, updateAuthRoleDto: UpdateAuthRoleDto) { public async update(roleId: string, updateAuthRoleDto: UpdateAuthRoleDto, pacInfo: PacInfoType) {
return `This action updates a #${id} authRole`; // ! 查找角色信息
const roleData = await this.getRoleForRoleId(roleId);
// ? 当不存在角色信息
if (roleData.length == 0) {
throw new HttpException('未找到目标角色信息,无法修改!', HttpStatus.BAD_REQUEST);
}
// ! 判断是否是root账户,非root账户无法设置为root
if (this.config.get('masterId') !== pacInfo.userId && isTrueEnum(roleData[0].root)) {
throw new HttpException('没有权限创建原始角色!', HttpStatus.UNAUTHORIZED);
}
// ! 加目标锁
const lock = await this.redisService.distributedLock('DICT' + updateAuthRoleDto.roleKey, updateAuthRoleDto.roleKey);
// ? 存在正在进行写入的角色
if (!lock) throw new HttpException('服务繁忙,角色标识重复!', HttpStatus.CONFLICT);
// @ 核心内容
try {
// ! 查重
const checkRepeat = await this.getRoleForRoleKey(updateAuthRoleDto.roleKey);
// ? 是否存在重复的角色
if (checkRepeat.length > 0 && checkRepeat[0].roleId != roleId) throw new HttpException('角色标识重复!', HttpStatus.CONFLICT);
// ! 修改角色数据
const result = await this.updateRole(roleId, updateAuthRoleDto, pacInfo.userId as any).catch((e) => {
this.logger.error(e.message + e.track.toString());
throw new HttpException('角色写入错误!', HttpStatus.INTERNAL_SERVER_ERROR);
});
// ! 增加关联菜单
await this.createMenuLink(roleData[0].roleId, updateAuthRoleDto.menuList, pacInfo.userId as any).catch((e) => {
this.logger.error(e.message + e.track.toString());
throw new HttpException('添加菜单关系出现错误,角色写入错误!', HttpStatus.INTERNAL_SERVER_ERROR);
});
// ! 增加关联部门
await this.createDeptLink(roleData[0].roleId, updateAuthRoleDto.deptList, pacInfo.userId as any).catch((e) => {
this.logger.error(e.message + e.track);
throw new HttpException('添加部门数据范围关系出现错误,角色写入错误!', HttpStatus.INTERNAL_SERVER_ERROR);
});
// ! 解锁
lock();
// ! 返回结果
return result;
} catch (e) {
// ! 解锁
lock();
// ! 抛出错误
throw e;
}
} }
remove(id: number) { /** Service
return `This action removes a #${id} authRole`; * NAME: remove
* DESC: 删除角色信息
* DATE: 2024-06-26 16:16:55 -
* */
public async remove(roleId: string, pacInfo: PacInfoType) {
return await this.deleteRole(roleId, pacInfo.userId as any);
} }
// DB 通过roleKey查找角色信息 // DB 通过roleKey查找角色信息
@ -179,30 +277,241 @@ export class AuthRoleService {
} }
// DB 建立菜单角色关联 // DB 建立菜单角色关联
private async createMenuLink(roleId, menuIdList, userId) { private async createMenuLink(roleId: string, menuIdList: string[], userId: string) {
const newMenuIdList = Array.from(new Set(menuIdList)); const newMenuIdList = Array.from(new Set(menuIdList));
await this.mysqlService.db.delete(pacAuthLinkRoleMenu).where(eq(pacAuthLinkRoleMenu.roleId as any, roleId)); await this.mysqlService.db.delete(pacAuthLinkRoleMenu).where(eq(pacAuthLinkRoleMenu.roleId as any, roleId));
await this.mysqlService.db.insert(pacAuthLinkRoleMenu).values( if (menuIdList.length > 0) {
newMenuIdList.map((i) => ({ await this.mysqlService.db.insert(pacAuthLinkRoleMenu).values(
roleId, newMenuIdList.map((i) => ({
menuId: i, roleId,
createby: userId, menuId: i,
createtime: sql`now()` as any, createby: userId,
})), createtime: sql`now()` as any,
); })),
);
}
} }
// DB 建立部门角色关联 // DB 建立部门角色关联
private async createDeptLink(roleId, deptIdList, userId) { private async createDeptLink(roleId: string, deptIdList: string[], userId: string) {
const newDeptIdList = Array.from(new Set(deptIdList)); const newDeptIdList = Array.from(new Set(deptIdList));
await this.mysqlService.db.delete(pacAuthLinkRoleDept).where(eq(pacAuthLinkRoleDept.roleId as any, roleId)); await this.mysqlService.db.delete(pacAuthLinkRoleDept).where(eq(pacAuthLinkRoleDept.roleId as any, roleId));
await this.mysqlService.db.insert(pacAuthLinkRoleDept).values( if (deptIdList.length > 0) {
newDeptIdList.map((i) => ({ await this.mysqlService.db.insert(pacAuthLinkRoleDept).values(
roleId, newDeptIdList.map((i) => ({
deptId: i, roleId,
createby: userId, deptId: i,
createtime: sql`now()` as any, createby: userId,
})), createtime: sql`now()` as any,
})),
);
}
}
// DB 查角色-基本查询结构
private getRoleData(data, selectData = undefined) {
// ! 定义基础查询函数
// 启用动态查询模式 $dynamic
const query = this.mysqlService.db
.select(selectData)
.from(pacAuthRole)
.orderBy(
isTrueEnum(data.isAsc) ? asc(pacAuthRole.orderNum) : desc(pacAuthRole.orderNum),
isTrueEnum(data.isAsc) ? asc(pacAuthRole.roleId) : desc(pacAuthRole.roleId),
)
.leftJoin(pacCoreDict, eq(pacAuthRole.roleType, pacCoreDict.dictId))
.$dynamic();
// 查询条件集合
const wl = [];
// ? 未删除
wl.push(isNull(pacAuthRole.deleteby));
// ? 模糊查询
wl.push(
or(
like(pacAuthRole.roleName, likeQuery(data.roleInfo)),
like(pacAuthRole.roleKey, likeQuery(data.roleInfo)),
like(pacAuthRole.roleDesc, likeQuery(data.roleInfo)),
).if(isExistKey(data, 'roleInfo')),
); );
// ? 是否查pac的数据
wl.push(eq(pacAuthRole.root, isTrueEnum(data['root']) ? 0 : 1).if(isExistKey(data, 'root') && isTrueEnum(data['root'])));
// ? 按照层级查
wl.push(eq(pacAuthRole.pid, data.hierarchy).if(isExistKey(data, 'hierarchy')));
// ? 是否查角色类型
wl.push(eq(pacAuthRole.roleType, data.roleType).if(isExistKey(data, 'roleType')));
// ? 是否查字典状态
wl.push(eq(pacAuthRole.status, data.status).if(isExistKey(data, 'status')));
query.where(and(...wl));
return query;
}
// DB 查角色分页
private async getRolePage(getPacAuthRoleAllDto: GetPacAuthRoleAllDto) {
const offset = (getPacAuthRoleAllDto.pageNumber - 1) * getPacAuthRoleAllDto.pageSize;
// ! 使用基础查询构建查询总记录数
const totalCountQuery = this.getRoleData(getPacAuthRoleAllDto, {
totalCount: sql`COUNT(*)`,
});
// ! 使用基础查询构建分页查询
// 重命名表
const userTable1 = alias(pacAuthUser, 'userTable1');
const paginatedQuery = this.getRoleData(getPacAuthRoleAllDto, {
...this.rolePageType,
updateName: userTable1.nickname,
})
.leftJoin(pacAuthUser, eq(pacAuthRole.createby, pacAuthUser.userId))
.leftJoin(userTable1, eq(pacAuthRole.updateby, pacAuthUser.userId))
.limit(getPacAuthRoleAllDto.pageSize)
.offset(offset);
return {
total: (await totalCountQuery)[0].totalCount,
rowData: await paginatedQuery,
searchData: getPacAuthRoleAllDto,
};
}
// DB 查角色列表
private getRoleList(getPacAuthRoleAllDto: GetPacAuthRoleAllDto) {
return this.getRoleData(getPacAuthRoleAllDto, this.roleListType);
}
// DB 查角色树
getRoleTree() {}
// DB 查角色详细信息
private async getRoleMore(roleId: string) {
// ! 定义2次连表查询的用户表
const userTable1 = alias(pacAuthUser, 'userTable1');
// ! 查询目标角色信息
const roleRerult = await this.mysqlService.db
.select({
...this.rolePageType,
updateName: userTable1.nickname,
})
.from(pacAuthRole)
.leftJoin(pacCoreDict, eq(pacAuthRole.roleType, pacCoreDict.dictId))
.leftJoin(pacAuthUser, eq(pacAuthRole.createby, pacAuthUser.userId))
.leftJoin(userTable1, eq(pacAuthRole.updateby, pacAuthUser.userId))
.where(and(isNull(pacAuthRole.deleteby), eq(pacAuthRole.roleId, roleId)));
// ! 如果不存在角色信息直接报错
if (roleRerult.length === 0) {
throw new HttpException('未找到目标角色详细信息!', HttpStatus.BAD_REQUEST);
}
// ! 获取角色关联的菜单信息
const menuList = await this.mysqlService.db
.select({
menuId: pacCoreMenu.menuId,
menuName: pacCoreMenu.menuName,
})
.from(pacCoreMenu)
.leftJoin(pacAuthLinkRoleMenu, eq(pacAuthLinkRoleMenu.menuId, pacCoreMenu.menuId))
.where(and(isNull(pacCoreMenu.deleteby), eq(pacAuthLinkRoleMenu.roleId, roleId)));
// ! 获取角色数据权限的部门范围
let deptList = [];
// ! 只有自定义数据范围才会选部门
if (roleRerult[0].deptScope == 5) {
deptList = await this.mysqlService.db
.select({
deptId: pacAuthDept.deptId,
deptName: pacAuthDept.deptName,
})
.from(pacAuthDept)
.leftJoin(pacAuthLinkRoleDept, eq(pacAuthLinkRoleDept.deptId, pacAuthDept.deptId))
.where(and(isNull(pacAuthDept.deleteby), eq(pacAuthLinkRoleDept.roleId, roleId)));
}
// ! 返回重构的数据结构
return {
...roleRerult[0],
menuList,
deptList,
};
}
// 根据ID查角色基本信息
private getRoleForRoleId(roleId: string) {
return this.mysqlService.db
.select()
.from(pacAuthRole)
.where(and(isNull(pacAuthRole.deleteby), eq(pacAuthRole.roleId, roleId)));
}
// DB 删除角色信息
private async deleteRole(roleId: string, userId: string) {
// ! 查找角色信息
const roleData = await this.getRoleForRoleId(roleId);
// ? 当不存在角色信息
if (roleData.length == 0) {
throw new HttpException('未找到目标角色信息,无法删除!', HttpStatus.BAD_REQUEST);
}
// ! 判断是否是root账户,非root账户无法设置为root
if (this.config.get('masterId') !== userId && isTrueEnum(roleData[0].root)) {
throw new HttpException('没有权限创建原始角色!', HttpStatus.UNAUTHORIZED);
}
// ? 判断是否存在子项
if (roleData[0].haveChildren != 0) {
throw new HttpException('该角色存在子项!', HttpStatus.BAD_REQUEST);
}
// ! 清角色菜单关联表
await this.mysqlService.db.delete(pacAuthLinkRoleMenu).where(eq(pacAuthLinkRoleMenu.roleId as any, roleId));
// ? 判断是否是自定义数据范围,清角色部门关联表
if (roleData[0].deptScope == 5) {
await this.mysqlService.db.delete(pacAuthLinkRoleDept).where(eq(pacAuthLinkRoleDept.roleId as any, roleId));
}
// ! 判断父节点是否存在
if (roleData[0].pid != 0) {
// ! 减少父级子节点数量
await this.haveChildrenSelfIncreasing(roleData[0].pid, false);
}
// ! 删除角色数据
return await this.mysqlService.db
.update(pacAuthRole)
.set({
deletetime: sql`now()`,
deleteby: userId,
})
.where(eq(pacAuthRole.roleId, roleId));
}
// DB 更新角色信息
private async updateRole(roleId: string, updateAuthRoleDto: UpdateAuthRoleDto, userId: string) {
return this.mysqlService.db
.update(pacAuthRole)
.set({
roleName: updateAuthRoleDto.roleName,
roleKey: updateAuthRoleDto.roleKey,
roleDesc: updateAuthRoleDto.roleDesc,
roleType: updateAuthRoleDto.roleType,
deptScope: updateAuthRoleDto.deptScope,
orderNum: updateAuthRoleDto.orderNum,
status: updateAuthRoleDto.status,
root: isTrueEnum(updateAuthRoleDto.root) ? 1 : 0,
updateby: userId,
updatetime: sql`now()`,
})
.where(eq(pacAuthRole.roleId, roleId));
} }
} }

@ -103,7 +103,7 @@ export class CreateAuthRoleDto {
minItems: 1, minItems: 1,
}) })
@IsString({ each: true, message: '部门id格式错误' }) @IsString({ each: true, message: '部门id格式错误' })
@ArrayMinSize(1, { message: '至少需要选择一个部门作为数据范围' }) @ArrayMinSize(0, { message: '至少需要选择一个部门作为数据范围' })
@Length(19, 19, { each: true, message: '部门id格式错误' }) @Length(19, 19, { each: true, message: '部门id格式错误' })
@IsOptional() @IsOptional()
readonly deptList?: string[]; readonly deptList?: string[];

@ -38,13 +38,14 @@ export class GetPacAuthRoleAllDto extends GetDto {
description: '角色类型,来自于字典', description: '角色类型,来自于字典',
type: String, type: String,
example: '0', example: '0',
required: true, required: false,
minLength: 19, minLength: 19,
maxLength: 19, maxLength: 19,
}) })
@Trim() @Trim()
@IsString({ message: '角色类型格式不正确!' }) @IsString({ message: '角色类型格式不正确!' })
@Length(19, 19, { message: '角色类型格式不正确!' }) @Length(19, 19, { message: '角色类型格式不正确!' })
@IsOptional()
readonly roleType: string; readonly roleType: string;
@ApiProperty({ @ApiProperty({

@ -1,4 +1,25 @@
import { PartialType } from '@nestjs/swagger'; import { ApiProperty, PartialType } from '@nestjs/swagger';
import { CreateAuthRoleDto } from './create-auth-role.dto'; import { CreateAuthRoleDto } from './create-auth-role.dto';
import { IsInt, IsOptional, Max, Min } from 'class-validator';
export class UpdateAuthRoleDto extends PartialType(CreateAuthRoleDto) {} export class UpdateAuthRoleDto extends PartialType(CreateAuthRoleDto) {
@ApiProperty({
description: '状态',
type: Number,
example: 10,
required: false,
minimum: -100,
maximum: 100,
})
@IsOptional()
@IsInt({
message: '状态必须是整数!',
})
@Min(-1000, {
message: '状态不能小于-100!',
})
@Max(1000, {
message: '状态不能超过100',
})
readonly status: number;
}

@ -10,7 +10,7 @@ import { Snowflake } from '@service/snowflake/snowflake.service';
import { GetPacCoreDictAllDto, PacCoreDictTargetListDto } from '@app/core-dict/dto/get-core-dict.dto'; import { GetPacCoreDictAllDto, PacCoreDictTargetListDto } from '@app/core-dict/dto/get-core-dict.dto';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { likeQuery } from '@utils/likeQuery'; import { likeQuery } from '@utils/likeQuery';
import { QueryBuilder } from 'drizzle-orm/mysql-core'; import { alias, QueryBuilder } from 'drizzle-orm/mysql-core';
import { PacInfoType } from '@utils/myType'; import { PacInfoType } from '@utils/myType';
import { isTrueEnum, isExistKey } from '@utils/boolean.enum'; import { isTrueEnum, isExistKey } from '@utils/boolean.enum';
import { customDrizzleRowWithRecursive } from '@utils/customDrizzleRowWithRecursive'; import { customDrizzleRowWithRecursive } from '@utils/customDrizzleRowWithRecursive';
@ -36,7 +36,6 @@ export class CoreDictService {
createName: pacAuthUser.nickname, createName: pacAuthUser.nickname,
createtime: pacCoreDict.createtime, createtime: pacCoreDict.createtime,
updateby: pacCoreDict.updateby, updateby: pacCoreDict.updateby,
updateName: pacAuthUser.nickname,
updatetime: pacCoreDict.updatetime, updatetime: pacCoreDict.updatetime,
}; };
@ -204,32 +203,31 @@ export class CoreDictService {
const result = await this.getMore(dictId); const result = await this.getMore(dictId);
// ? 判断是否存在 // ? 判断是否存在
if (result.length > 0) { if (result.length == 0) {
// ! root数据,非root用户不允许删除 throw new HttpException('未找到目标字典信息, 无法删除!', HttpStatus.BAD_REQUEST);
if (result[0].root && this.config.get<number>('masterId') !== pacInfo.userId) { }
throw new HttpException('原始字典,权限不足无法删除!', HttpStatus.BAD_REQUEST);
}
// ! 存在目标字典项 // ! root数据,非root用户不允许删除
if (result[0].root && this.config.get<number>('masterId') !== pacInfo.userId) {
throw new HttpException('原始字典,权限不足无法删除!', HttpStatus.BAD_REQUEST);
}
// ? 判断是否存在子项 // ! 存在目标字典项
if (result[0].haveChildren == 0) {
// ! 删除字典
await this.deleteDictItem(dictId, pacInfo);
} else {
throw new HttpException('该字典存在子项!', HttpStatus.BAD_REQUEST);
}
// ! 判断父节点是否存在 // ? 判断是否存在子项
if (result[0].pid != 0) { if (result[0].haveChildren == 0) {
// ! 减少父级子节点数量 // ! 删除字典
await this.haveChildrenSelfIncreasing(result[0].pid, false); await this.deleteDictItem(dictId, pacInfo);
}
return '删除字典成功';
} else { } else {
// ! 不存在目标字典项,直接返回 throw new HttpException('该字典存在子项!', HttpStatus.BAD_REQUEST);
return '删除字典成功'; }
// ! 判断父节点是否存在
if (result[0].pid != 0) {
// ! 减少父级子节点数量
await this.haveChildrenSelfIncreasing(result[0].pid, false);
} }
return '删除字典成功';
} }
// DB 根据serviceKey查找服务数据 可用于查重 // DB 根据serviceKey查找服务数据 可用于查重
@ -332,8 +330,11 @@ export class CoreDictService {
}); });
// 使用基础查询构建分页查询 // 使用基础查询构建分页查询
const paginatedQuery = this.getDict(getCoreDictAllDto, this.dictMoreDataType) // 重命名表
const userTable1 = alias(pacAuthUser, 'userTable1');
const paginatedQuery = this.getDict(getCoreDictAllDto, { ...this.dictMoreDataType, updateName: userTable1.nickname })
.leftJoin(pacAuthUser, eq(pacCoreDict.createby, pacAuthUser.userId)) .leftJoin(pacAuthUser, eq(pacCoreDict.createby, pacAuthUser.userId))
.leftJoin(userTable1, eq(pacCoreDict.updateby, userTable1.userId))
.leftJoin(pacCoreService, eq(pacCoreService.serviceKey, pacCoreDict.serviceKey)) .leftJoin(pacCoreService, eq(pacCoreService.serviceKey, pacCoreDict.serviceKey))
.limit(getCoreDictAllDto.pageSize) .limit(getCoreDictAllDto.pageSize)
.offset(offset); .offset(offset);
@ -347,10 +348,13 @@ export class CoreDictService {
// DB 通过ID查找Dict详细信息 // DB 通过ID查找Dict详细信息
private async getMore(dictId: string) { private async getMore(dictId: string) {
// 重命名表
const userTable1 = alias(pacAuthUser, 'userTable1');
return this.mysqlService.db return this.mysqlService.db
.select(this.dictMoreDataType) .select({ ...this.dictMoreDataType, updateName: userTable1.nickname })
.from(pacCoreDict) .from(pacCoreDict)
.leftJoin(pacAuthUser, eq(pacCoreDict.createby, pacAuthUser.userId)) .leftJoin(pacAuthUser, eq(pacCoreDict.createby, pacAuthUser.userId))
.leftJoin(userTable1, eq(pacCoreDict.updateby, userTable1.userId))
.leftJoin(pacCoreService, eq(pacCoreService.serviceKey, pacCoreDict.serviceKey)) .leftJoin(pacCoreService, eq(pacCoreService.serviceKey, pacCoreDict.serviceKey))
.where(and(eq(pacCoreDict.dictId, dictId), isNull(pacCoreDict.deleteby))); .where(and(eq(pacCoreDict.dictId, dictId), isNull(pacCoreDict.deleteby)));
} }
@ -387,10 +391,13 @@ export class CoreDictService {
); );
} else { } else {
// ! 查询自己 // ! 查询自己
// 重命名表
const userTable1 = alias(pacAuthUser, 'userTable1');
return this.mysqlService.db return this.mysqlService.db
.select(this.dictMoreDataType) .select({ ...this.dictMoreDataType, updateName: userTable1.nickname })
.from(pacCoreDict) .from(pacCoreDict)
.leftJoin(pacAuthUser, eq(pacCoreDict.createby, pacAuthUser.userId)) .leftJoin(pacAuthUser, eq(pacCoreDict.createby, pacAuthUser.userId))
.leftJoin(userTable1, eq(pacCoreDict.updateby, userTable1.userId))
.leftJoin(pacCoreService, eq(pacCoreService.serviceKey, pacCoreDict.serviceKey)) .leftJoin(pacCoreService, eq(pacCoreService.serviceKey, pacCoreDict.serviceKey))
.where(and(eq(pacCoreDict.dictKey, dictKey), isNull(pacCoreDict.deleteby))); .where(and(eq(pacCoreDict.dictKey, dictKey), isNull(pacCoreDict.deleteby)));
} }

@ -44,7 +44,7 @@ export class GetPacCoreDictAllDto extends GetDto {
maxLength: 19, maxLength: 19,
}) })
@Trim() @Trim()
@Length(19, 19, { message: '字典类型格式不正确!' }) @Length(1, 19, { message: '字典类型格式不正确!' })
@IsString({ message: '字典类型应为字符串格式!' }) @IsString({ message: '字典类型应为字符串格式!' })
@IsOptional() @IsOptional()
readonly dictType?: string; readonly dictType?: string;

@ -11,7 +11,7 @@ import { and, asc, desc, eq, isNull, like, or, sql } from 'drizzle-orm';
import { isExistKey, isTrueEnum } from '@utils/boolean.enum'; import { isExistKey, isTrueEnum } from '@utils/boolean.enum';
import { CoreEnvKeyDTO, CoreEnvTargetListDTO, GetCoreEnvDTO } from '@app/core-env/dto/get-core-env.dto'; import { CoreEnvKeyDTO, CoreEnvTargetListDTO, GetCoreEnvDTO } from '@app/core-env/dto/get-core-env.dto';
import { likeQuery } from '@utils/likeQuery'; import { likeQuery } from '@utils/likeQuery';
import { QueryBuilder } from 'drizzle-orm/mysql-core'; import { QueryBuilder, alias } from 'drizzle-orm/mysql-core';
import { customDrizzleRowWithRecursive } from '@utils/customDrizzleRowWithRecursive'; import { customDrizzleRowWithRecursive } from '@utils/customDrizzleRowWithRecursive';
import { PacInfoType } from '@utils/myType'; import { PacInfoType } from '@utils/myType';
@ -340,8 +340,11 @@ export class CoreEnvService {
}); });
// 使用基础查询构建分页查询 // 使用基础查询构建分页查询
const paginatedQuery = this.getEnv(getCoreEnvDTO, this.envMoreDataType) // 重命名表
const userTable1 = alias(pacAuthUser, 'userTable1');
const paginatedQuery = this.getEnv(getCoreEnvDTO, { ...this.envMoreDataType, updateName: userTable1.nickname })
.leftJoin(pacAuthUser, eq(pacCoreEnv.createby, pacAuthUser.userId)) .leftJoin(pacAuthUser, eq(pacCoreEnv.createby, pacAuthUser.userId))
.leftJoin(userTable1, eq(pacCoreEnv.updateby, userTable1.userId))
.leftJoin(pacCoreService, eq(pacCoreEnv.serviceKey, pacCoreService.serviceKey)) .leftJoin(pacCoreService, eq(pacCoreEnv.serviceKey, pacCoreService.serviceKey))
.limit(getCoreEnvDTO.pageSize) .limit(getCoreEnvDTO.pageSize)
.offset(offset); .offset(offset);
@ -355,10 +358,13 @@ export class CoreEnvService {
// DB 通过ID查找Env详细信息 // DB 通过ID查找Env详细信息
private getMore(envId: string) { private getMore(envId: string) {
// 重命名表
const userTable1 = alias(pacAuthUser, 'userTable1');
return this.mysqlService.db return this.mysqlService.db
.select(this.envMoreDataType) .select({ ...this.envMoreDataType, updateName: userTable1.nickname })
.from(pacCoreEnv) .from(pacCoreEnv)
.leftJoin(pacAuthUser, eq(pacCoreEnv.createby, pacAuthUser.userId)) .leftJoin(pacAuthUser, eq(pacCoreEnv.createby, pacAuthUser.userId))
.leftJoin(userTable1, eq(pacCoreEnv.updateby, userTable1.userId))
.leftJoin(pacCoreService, eq(pacCoreEnv.serviceKey, pacCoreService.serviceKey)) .leftJoin(pacCoreService, eq(pacCoreEnv.serviceKey, pacCoreService.serviceKey))
.leftJoin(pacCoreDict, and(eq(pacCoreDict.dictId, pacCoreEnv.envVal), eq(pacCoreEnv.valIsDict, 1))) .leftJoin(pacCoreDict, and(eq(pacCoreDict.dictId, pacCoreEnv.envVal), eq(pacCoreEnv.valIsDict, 1)))
.where(and(eq(pacCoreEnv.envId, envId), isNull(pacCoreEnv.deleteby))); .where(and(eq(pacCoreEnv.envId, envId), isNull(pacCoreEnv.deleteby)));
@ -399,10 +405,13 @@ export class CoreEnvService {
return this.mysqlService.db.execute(SQL); return this.mysqlService.db.execute(SQL);
} else { } else {
// ! 查询自己 // ! 查询自己
// 重命名表
const userTable1 = alias(pacAuthUser, 'userTable1');
return this.mysqlService.db return this.mysqlService.db
.select(this.envMoreDataType) .select({ ...this.envMoreDataType, updateName: userTable1.nickname })
.from(pacCoreEnv) .from(pacCoreEnv)
.leftJoin(pacAuthUser, eq(pacCoreEnv.createby, pacAuthUser.userId)) .leftJoin(pacAuthUser, eq(pacCoreEnv.createby, pacAuthUser.userId))
.leftJoin(userTable1, eq(pacCoreEnv.updateby, userTable1.userId))
.leftJoin(pacCoreService, eq(pacCoreEnv.serviceKey, pacCoreService.serviceKey)) .leftJoin(pacCoreService, eq(pacCoreEnv.serviceKey, pacCoreService.serviceKey))
.leftJoin(pacCoreDict, and(eq(pacCoreDict.dictId, pacCoreEnv.envVal), eq(pacCoreEnv.valIsDict, 1))) .leftJoin(pacCoreDict, and(eq(pacCoreDict.dictId, pacCoreEnv.envVal), eq(pacCoreEnv.valIsDict, 1)))
.where(and(eq(pacCoreEnv.envKey, coreEnvKeyDTO.envKey), isNull(pacCoreEnv.deleteby))); .where(and(eq(pacCoreEnv.envKey, coreEnvKeyDTO.envKey), isNull(pacCoreEnv.deleteby)));

@ -12,6 +12,7 @@ import { eq, sql, isNull, asc, desc, or, like, and } from 'drizzle-orm';
import { isExistKey, isTrueEnum } from '@utils/boolean.enum'; import { isExistKey, isTrueEnum } from '@utils/boolean.enum';
import { GetPacCoreMenuAllDto } from '@app/core-menu/dto/get-core-menu.dto'; import { GetPacCoreMenuAllDto } from '@app/core-menu/dto/get-core-menu.dto';
import { likeQuery } from '@utils/likeQuery'; import { likeQuery } from '@utils/likeQuery';
import { alias } from 'drizzle-orm/mysql-core';
@Injectable() @Injectable()
export class CoreMenuService { export class CoreMenuService {
@ -40,7 +41,6 @@ export class CoreMenuService {
createName: pacAuthUser.nickname, createName: pacAuthUser.nickname,
createtime: pacCoreMenu.createtime, createtime: pacCoreMenu.createtime,
updateby: pacCoreMenu.updateby, updateby: pacCoreMenu.updateby,
updateName: pacAuthUser.nickname,
updatetime: pacCoreMenu.updatetime, updatetime: pacCoreMenu.updatetime,
}; };
@ -252,8 +252,11 @@ export class CoreMenuService {
}); });
// 使用基础查询构建分页查询 // 使用基础查询构建分页查询
const paginatedQuery = this.getMenuData(getPacCoreMenuAllDto, pacInfo, this.menuMoreDataType) // 重命名表
const userTable1 = alias(pacAuthUser, 'userTable1');
const paginatedQuery = this.getMenuData(getPacCoreMenuAllDto, pacInfo, { ...this.menuMoreDataType, createName: userTable1.nickname })
.leftJoin(pacAuthUser, eq(pacCoreMenu.createby, pacAuthUser.userId)) .leftJoin(pacAuthUser, eq(pacCoreMenu.createby, pacAuthUser.userId))
.leftJoin(userTable1, eq(pacCoreMenu.updateby, userTable1.userId))
.limit(getPacCoreMenuAllDto.pageSize) .limit(getPacCoreMenuAllDto.pageSize)
.offset(offset); .offset(offset);

Loading…
Cancel
Save