60
src/models/actions/create/CreatePermission.ts
Normal file
60
src/models/actions/create/CreatePermission.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import {
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsNotEmpty
|
||||
} from "class-validator";
|
||||
import { getConnectionManager } from 'typeorm';
|
||||
import { PrincipalNotFoundError } from '../../errors/PrincipalErrors';
|
||||
import { Permission } from '../entities/Permission';
|
||||
import { Principal } from '../entities/Principal';
|
||||
import { PermissionAction } from '../enums/PermissionAction';
|
||||
import { PermissionTarget } from '../enums/PermissionTargets';
|
||||
|
||||
/**
|
||||
* This classed is used to create a new Permission entity from a json body (post request).
|
||||
*/
|
||||
export class CreatePermission {
|
||||
|
||||
/**
|
||||
* The new permissions's principal's id.
|
||||
*/
|
||||
@IsInt()
|
||||
@IsNotEmpty()
|
||||
principal: number;
|
||||
|
||||
/**
|
||||
* The new permissions's target.
|
||||
*/
|
||||
@IsNotEmpty()
|
||||
@IsEnum(PermissionTarget)
|
||||
target: PermissionTarget;
|
||||
|
||||
/**
|
||||
* The new permissions's action.
|
||||
*/
|
||||
@IsNotEmpty()
|
||||
@IsEnum(PermissionAction)
|
||||
action: PermissionAction;
|
||||
|
||||
/**
|
||||
* Creates a new Permission entity from this.
|
||||
*/
|
||||
public async toPermission(): Promise<Permission> {
|
||||
let newPermission: Permission = new Permission();
|
||||
|
||||
newPermission.principal = await this.getPrincipal();
|
||||
newPermission.target = this.target;
|
||||
newPermission.action = this.action;
|
||||
|
||||
return newPermission;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the new permission's principal by it's id.
|
||||
*/
|
||||
public async getPrincipal(): Promise<Principal> {
|
||||
let principal = await getConnectionManager().get().getRepository(Principal).findOne({ id: this.principal })
|
||||
if (!principal) { throw new PrincipalNotFoundError(); }
|
||||
return principal;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user