backend/src/models/creation/CreateRunner.ts

68 lines
2.2 KiB
TypeScript

import { IsInt, IsOptional } from 'class-validator';
import { getConnectionManager } from 'typeorm';
import { RunnerGroupNeededError, RunnerGroupNotFoundError, RunnerOnlyOneGroupAllowedError } from '../../errors/RunnerErrors';
import { Runner } from '../entities/Runner';
import { RunnerGroup } from '../entities/RunnerGroup';
import { RunnerOrganisation } from '../entities/RunnerOrganisation';
import { RunnerTeam } from '../entities/RunnerTeam';
import { CreateParticipant } from './CreateParticipant';
export class CreateRunner extends CreateParticipant {
/**
* The new runner's team's id.
* Either provide this or his organisation's id.
*/
@IsInt()
@IsOptional()
teamId?: number;
/**
* The new runner's organisation's id.
* Either provide this or his teams's id.
*/
@IsInt()
@IsOptional()
orgId?: number;
/**
* Creates a Runner entity from this.
*/
public async toRunner(): Promise<Runner> {
let newRunner: Runner = new Runner();
newRunner.firstname = this.firstname;
newRunner.middlename = this.middlename;
newRunner.lastname = this.lastname;
newRunner.phone = this.phone;
newRunner.email = this.email;
newRunner.group = await this.getGroup();
newRunner.address = await this.getAddress();
return newRunner;
}
/**
* Manages all the different ways a group can be provided.
*/
public async getGroup(): Promise<RunnerGroup> {
let group: RunnerGroup;
if (this.teamId !== undefined && this.orgId !== undefined) {
throw new RunnerOnlyOneGroupAllowedError();
}
if (this.teamId === undefined && this.orgId === undefined) {
throw new RunnerGroupNeededError();
}
if (this.teamId) {
group = await getConnectionManager().get().getRepository(RunnerTeam).findOne({ id: this.teamId });
}
if (this.orgId) {
group = await getConnectionManager().get().getRepository(RunnerOrganisation).findOne({ id: this.orgId });
}
if (!group) {
throw new RunnerGroupNotFoundError();
}
return group;
}
}