76 lines
2.7 KiB
TypeScript
76 lines
2.7 KiB
TypeScript
import { DeleteResult, EntityManager, InsertResult } from "typeorm";
|
|
import { dataSource } from "../../../data-source";
|
|
import { user } from "../../../entity/management/user";
|
|
import { userPermission } from "../../../entity/management/user_permission";
|
|
import InternalException from "../../../exceptions/internalException";
|
|
import {
|
|
CreateUserPermissionCommand,
|
|
DeleteUserPermissionCommand,
|
|
UpdateUserPermissionsCommand,
|
|
} from "./userPermissionCommand";
|
|
import UserPermissionService from "../../../service/management/userPermissionService";
|
|
import PermissionHelper from "../../../helpers/permissionHelper";
|
|
import { PermissionString } from "../../../type/permissionTypes";
|
|
import DatabaseActionException from "../../../exceptions/databaseActionException";
|
|
|
|
export default abstract class UserPermissionCommandHandler {
|
|
/**
|
|
* @description update user permissions
|
|
* @param {UpdateUserPermissionsCommand} updateUserPermissions
|
|
* @returns {Promise<void>}
|
|
*/
|
|
static async updatePermissions(updateUserPermissions: UpdateUserPermissionsCommand): Promise<void> {
|
|
let currentPermissions = (await UserPermissionService.getByUser(updateUserPermissions.userId)).map(
|
|
(r) => r.permission
|
|
);
|
|
return await dataSource.manager
|
|
.transaction(async (manager) => {
|
|
let newPermissions = PermissionHelper.getWhatToAdd(currentPermissions, updateUserPermissions.permissions);
|
|
let removePermissions = PermissionHelper.getWhatToRemove(currentPermissions, updateUserPermissions.permissions);
|
|
|
|
if (newPermissions.length != 0) {
|
|
await this.updatePermissionsAdd(manager, updateUserPermissions.userId, newPermissions);
|
|
}
|
|
if (removePermissions.length != 0) {
|
|
await this.updatePermissionsRemove(manager, updateUserPermissions.userId, removePermissions);
|
|
}
|
|
})
|
|
.then(() => {})
|
|
.catch((err) => {
|
|
throw new DatabaseActionException("UPDATE", "userPermissions", err);
|
|
});
|
|
}
|
|
|
|
private static async updatePermissionsAdd(
|
|
manager: EntityManager,
|
|
userId: string,
|
|
permissions: Array<PermissionString>
|
|
): Promise<InsertResult> {
|
|
return await manager
|
|
.createQueryBuilder()
|
|
.insert()
|
|
.into(userPermission)
|
|
.values(
|
|
permissions.map((p) => ({
|
|
permission: p,
|
|
userId: userId,
|
|
}))
|
|
)
|
|
.orIgnore()
|
|
.execute();
|
|
}
|
|
|
|
private static async updatePermissionsRemove(
|
|
manager: EntityManager,
|
|
userId: string,
|
|
permissions: Array<PermissionString>
|
|
): Promise<DeleteResult> {
|
|
return await manager
|
|
.createQueryBuilder()
|
|
.delete()
|
|
.from(userPermission)
|
|
.where("userId = :id", { id: userId })
|
|
.andWhere("permission IN (:...permission)", { permission: permissions })
|
|
.execute();
|
|
}
|
|
}
|