Skip to content

Commit

Permalink
feat: 单独抽取vo层
Browse files Browse the repository at this point in the history
  • Loading branch information
kuangshp committed Jul 19, 2021
1 parent 380035d commit 5f220dd
Show file tree
Hide file tree
Showing 15 changed files with 63 additions and 62 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { QueryVo } from '@src/dto/query.vo';
import { QueryListVo } from '@src/dto/query.list.vo';
import { QueryVo } from '@src/vo/query.vo';
import { QueryListVo } from '@src/vo/query.list.vo';
import { ApiProperty } from '@nestjs/swagger';

export class AccessVo extends QueryVo {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { QueryVo } from '@src/dto/query.vo';
import { QueryVo } from '@src/vo/query.vo';
import { ApiProperty } from '@nestjs/swagger';

export class MenusListVo extends QueryVo {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';
import { QueryListVo } from '@src/dto/query.list.vo';
import { QueryVo } from '@src/dto/query.vo';
import { QueryListVo } from '@src/vo/query.list.vo';
import { QueryVo } from '@src/vo/query.vo';

export class AccountVo extends QueryVo {
@ApiProperty({ description: '用户名' })
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ApiProperty } from '@nestjs/swagger';
import { QueryVo } from '@src/dto/query.vo';
import { QueryVo } from '@src/vo/query.vo';

export class LoginVo extends QueryVo {
@ApiProperty({ description: '账号绑定的手机号码' })
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RoleEntity } from './../../../role/entities/role.entity';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { AccountRoleEntity } from '../../entities/account.role.entity';
import { Repository, getManager, EntityManager, getConnection } from 'typeorm';
Expand All @@ -11,6 +11,7 @@ import { DistributionRoleDto } from '../../controllers/account-role/dto/distribu

@Injectable()
export class AccountRoleService {
private readonly logger: Logger = new Logger(AccountRoleService.name);
constructor(
@InjectRepository(AccountRoleEntity)
private readonly accountRoleRepository: Repository<AccountRoleEntity>,
Expand Down Expand Up @@ -45,18 +46,22 @@ export class AccountRoleService {
.transaction(async (entityManager: EntityManager) => {
await entityManager.delete<AccountRoleEntity>(AccountRoleEntity, { accountId });
for (const item of roleList) {
const result = entityManager.create<AccountRoleEntity>(AccountRoleEntity, {
accountId,
roleId: item,
});
const result: AccountRoleEntity = entityManager.create<AccountRoleEntity>(
AccountRoleEntity,
{
accountId,
roleId: item,
},
);
await entityManager.save(result);
}
})
.then(() => {
return '分配角色成功';
})
.catch((e: HttpException) => {
throw new HttpException(`给账号分配角色失败:${e}`, HttpStatus.OK);
this.logger.error('给账号分配角色错误', e.message);
throw new HttpException(`给账号分配角色失败:${e.message}`, HttpStatus.OK);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ export class AccountService {
throw new HttpException('系统默认生成的账号不能修改信息', HttpStatus.OK);
}
const { username, email, mobile, status, platform } = updateAccountDto;
const result = await this.accountRepository.findOne(id);
const result: AccountEntity | undefined = await this.accountRepository.findOne(id);
await this.accountRepository.save(
Object.assign(result, { username, email, mobile, status, platform }),
);
Expand Down Expand Up @@ -269,7 +269,7 @@ export class AccountService {
.where(mapToObj(query))
.getCount();
// 处理当前手机号码或者邮箱不合法的时候
const formatData = data.map((item) => {
const formatData: AccountVo[] = data.map((item) => {
const { username, mobile, email } = item;
return {
...item,
Expand Down
19 changes: 8 additions & 11 deletions src/modules/admin/system/account/services/login/login.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { LoginDto } from '../../controllers/login/dto/login.dto';
import { AccountEntity } from '../../entities/account.entity';
import { InjectRepository } from '@nestjs/typeorm';
Expand All @@ -10,6 +10,7 @@ import { LoginVo } from '../../controllers/login/vo/login.vo';

@Injectable()
export class LoginService {
private logger: Logger = new Logger(LoginService.name);
constructor(
@InjectRepository(AccountEntity)
private readonly accountRepository: Repository<AccountEntity>,
Expand All @@ -33,50 +34,46 @@ export class LoginService {
let sqlPassword: string | undefined;
let findAccount: AccountEntity | undefined;
if (isMobilePhone(username, 'zh-CN')) {
const findResult: AccountEntity | undefined = await getConnection()
const findResult: Pick<AccountEntity, 'password'> | undefined = await getConnection()
.createQueryBuilder(AccountEntity, 'account')
.select([])
.addSelect('account.password', 'password')
.where('(account.mobile = :mobile)', { mobile: username })
.getRawOne();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
sqlPassword = findResult?.password;
findAccount = await this.accountRepository.findOne({ where: { mobile: username } });
} else if (isEmail(username)) {
const findResult: AccountEntity | undefined = await getConnection()
const findResult: Pick<AccountEntity, 'password'> | undefined = await getConnection()
.createQueryBuilder(AccountEntity, 'account')
.select([])
.addSelect('account.password', 'password')
.where('(account.email = :email)', { email: username })
.getRawOne();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
sqlPassword = findResult?.password;
findAccount = await this.accountRepository.findOne({ where: { email: username } });
} else {
const findResult: AccountEntity | undefined = await getConnection()
const findResult: Pick<AccountEntity, 'password'> | undefined = await getConnection()
.createQueryBuilder(AccountEntity, 'account')
.select([])
.addSelect('account.password', 'password')
.where('(account.username = :username)', { username })
.getRawOne();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
sqlPassword = findResult?.password;
findAccount = await this.accountRepository.findOne({ where: { username } });
}
if (sqlPassword && this.toolsService.checkPassword(password, sqlPassword) && findAccount) {
const lastLogin = this.accountLastLoginRepository.create({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
accountId: findAccount!.id,
accountId: findAccount.id,
lastLoginIp: ipAddress,
});
await this.accountLastLoginRepository.save(lastLogin);
console.log(findAccount, '当前用户');
this.logger.log('当前用户', findAccount);
return Object.assign(findAccount, { token: this.toolsService.generateToken(findAccount) });
} else {
throw new HttpException('用户名或密码错误', HttpStatus.OK);
}
} catch (e) {
console.log(e, '?');
this.logger.error('用户名或密码错误', e);
throw new HttpException('用户名或密码错误', HttpStatus.OK);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/modules/admin/system/role/controllers/role/vo/role.vo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';
import { QueryVo } from '@src/dto/query.vo';
import { QueryListVo } from '@src/dto/query.list.vo';
import { QueryListVo } from '@src/vo/query.list.vo';
import { QueryVo } from '@src/vo/query.vo';

export class RoleVo extends QueryVo {
@ApiProperty({ description: '角色名称' })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,22 @@ export class RoleAccessService {
* @return {*}
*/
async allMenus(): Promise<AllMenusVo[]> {
const menusList = await this.accessRepository.find({
where: [{ type: AccessTypeEnum.MODULE }, { type: AccessTypeEnum.MENUS }],
select: ['id', 'moduleName', 'actionName', 'parentId'],
order: { sort: 'ASC', createdAt: 'DESC' },
});
return menusList.map((item: AccessEntity) => {
return {
id: item.id,
key: String(item.id),
title: item.moduleName ? item.moduleName : item.actionName,
parentId: item.parentId,
};
});
const menusList: Pick<AccessEntity, 'id' | 'moduleName' | 'actionName' | 'parentId'>[] =
await this.accessRepository.find({
where: [{ type: AccessTypeEnum.MODULE }, { type: AccessTypeEnum.MENUS }],
select: ['id', 'moduleName', 'actionName', 'parentId'],
order: { sort: 'ASC', createdAt: 'DESC' },
});
return menusList.map(
(item: Pick<AccessEntity, 'id' | 'moduleName' | 'actionName' | 'parentId'>) => {
return {
id: item.id,
key: String(item.id),
title: item.moduleName ? item.moduleName : item.actionName,
parentId: item.parentId,
};
},
);
}

/**
Expand Down
29 changes: 14 additions & 15 deletions src/modules/admin/system/role/services/role/role.service.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { RoleEntity } from '../../entities/role.entity';
import { Repository, getConnection } from 'typeorm';
import { Repository, getConnection, ILike, Equal } from 'typeorm';
import { CreateRoleDto } from '../../controllers/role/dto/create.role.dto';
import { UpdateRoleDto } from '../../controllers/role/dto/update.role.dto';
import { RoleListVo, RoleVo } from '../../controllers/role/vo/role.vo';
import { RoleReqDto } from '../../controllers/role/dto/role.req.dto';
import { PageEnum, StatusEnum } from '@src/enums';
import { RoleEnum } from '@src/enums/role.enum';
import { AccountRoleEntity } from '../../../account/entities/account.role.entity';
import { mapToObj } from '@src/utils';

@Injectable()
export class RoleService {
Expand All @@ -29,21 +30,24 @@ export class RoleService {
*/
async createRole(createRoleDto: CreateRoleDto): Promise<string> {
const { name, isDefault } = createRoleDto;
const findNameResult = await this.roleRepository.findOne({ where: { name }, select: ['id'] });
const findNameResult: Pick<RoleEntity, 'id'> | undefined = await this.roleRepository.findOne({
where: { name },
select: ['id'],
});
if (findNameResult) {
throw new HttpException(`${name}当前角色已经存在,不能重复创建`, HttpStatus.OK);
}
// 如果是默认角色的时候要判断下
if (Object.is(isDefault, RoleEnum.DEFAULT)) {
const findDefault = await this.roleRepository.findOne({
const findDefault: Pick<RoleEntity, 'id'> | undefined = await this.roleRepository.findOne({
where: { isDefault },
select: ['id'],
});
if (findDefault) {
throw new HttpException('已经存在默认角色不能重复创建', HttpStatus.OK);
}
}
const role = this.roleRepository.create(createRoleDto);
const role: RoleEntity = this.roleRepository.create(createRoleDto);
await this.roleRepository.save(role);
return '创建角色成功';
}
Expand All @@ -58,7 +62,7 @@ export class RoleService {
*/
async destroyRoleById(id: number): Promise<string> {
// 判断当前角色是否已经被占用(有账号绑定了该角色)
const accountRoleFindResult: AccountRoleEntity | undefined =
const accountRoleFindResult: Pick<AccountRoleEntity, 'id'> | undefined =
await this.accountRoleRepository.findOne({
where: { roleId: id },
select: ['id'],
Expand Down Expand Up @@ -133,21 +137,16 @@ export class RoleService {
name,
status,
} = roleReqDto;
const queryConditionList = [];
const query = new Map();
if (name) {
queryConditionList.push('role.name LIKE :name');
query.set('name', ILike(name));
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
if (
/^\d$/.test(String(status)) &&
[StatusEnum.NORMAL, StatusEnum.FORBIDDEN].includes(Number(status))
) {
queryConditionList.push('role.status = :status');
if ([StatusEnum.NORMAL, StatusEnum.FORBIDDEN].includes(Number(status))) {
query.set('status', Equal(status));
}
const queryCondition = queryConditionList.join(' AND ');
const [data, total] = await getConnection()
.createQueryBuilder(RoleEntity, 'role')
.where(queryCondition, { name: `%${name}%`, status })
.where(mapToObj(query))
.skip((pageNumber - 1) * pageSize)
.take(pageSize)
.printSql()
Expand Down
7 changes: 3 additions & 4 deletions src/modules/shared/services/init-db/init-db.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AccessEntity } from '@src/modules/admin/system/access/entities/access.entity';
import adminConfig from '@src/config/admin.config';
import { ObjectType } from '@src/types/obj-type';

@Injectable()
export class InitDbService {
Expand All @@ -30,8 +29,8 @@ export class InitDbService {
* @return {*}
*/
private async initAccount(): Promise<void> {
const username = adminConfig.defaultAccount;
const password = adminConfig.defaultPassword;
const username: string = adminConfig.defaultAccount;
const password: string = adminConfig.defaultPassword;
const isExist = await this.accountRepository.findOne({ where: { username } });
if (!isExist) {
const account = this.accountRepository.create({ username, password, isSuper: 1 });
Expand All @@ -48,7 +47,7 @@ export class InitDbService {
* @return {*}
*/
private async initAccess(): Promise<void> {
const accessList: ObjectType[] = [
const accessList: Record<string, number | string>[] = [
{
moduleName: '系统管理',
parentId: 0,
Expand Down
1 change: 0 additions & 1 deletion src/types/obj-type.ts

This file was deleted.

3 changes: 1 addition & 2 deletions src/utils/map.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { ObjectType } from '@src/types/obj-type';

type ObjectType = Record<string, number | string | boolean>;
/**
* @Author: 水痕
* @Date: 2021-03-26 14:35:21
Expand Down
File renamed without changes.
File renamed without changes.

0 comments on commit 5f220dd

Please sign in to comment.