backend/src/models/actions/UpdatePermission.ts
Nicolai Ort 1d0d79f3da First part of the action comment refactoring
ref #39
Why did i volunteer for this? It's just a glorified sleeping aid 😴
2020-12-21 16:08:10 +01:00

68 lines
2.1 KiB
TypeScript

import { IsInt, IsNotEmpty, IsObject } from 'class-validator';
import { getConnectionManager } from 'typeorm';
import { PermissionNeedsPrincipalError } from '../../errors/PermissionErrors';
import { PrincipalNotFoundError, PrincipalWrongTypeError } from '../../errors/PrincipalErrors';
import { Permission } from '../entities/Permission';
import { Principal } from '../entities/Principal';
import { PermissionAction } from '../enums/PermissionAction';
import { PermissionTarget } from '../enums/PermissionTargets';
/**
* This class is used to update a Permission entity (via put request).
*/
export class UpdatePermission {
/**
* The updated permission's id.
* This shouldn't have changed but it is here in case anyone ever wants to enable id changes (whyever they would want to).
*/
@IsInt()
id: number;
/**
* The updated permissions's principal.
* Just has to contain the principal's id -everything else won't be checked or changed.
*/
@IsObject()
@IsNotEmpty()
principal: Principal;
/**
* The permissions's target.
*/
@IsNotEmpty()
target: PermissionTarget;
/**
* The permissions's action.
*/
@IsNotEmpty()
action: PermissionAction;
/**
* Updates a provided Permission entity based on this.
*/
public async updatePermission(permission: Permission): Promise<Permission> {
permission.principal = await this.getPrincipal();
permission.target = this.target;
permission.action = this.action;
return permission;
}
/**
* Loads the updated permission's principal based on it's id.
*/
public async getPrincipal(): Promise<Principal> {
if (this.principal === undefined || this.principal === null) {
throw new PermissionNeedsPrincipalError();
}
if (!isNaN(this.principal.id)) {
let principal = await getConnectionManager().get().getRepository(Principal).findOne({ id: this.principal.id });
if (!principal) { throw new PrincipalNotFoundError(); }
return principal;
}
throw new PrincipalWrongTypeError();
}
}