import { IsEmail, IsNotEmpty, IsObject, IsOptional, IsPhoneNumber, IsString } from 'class-validator'; import { getConnectionManager } from 'typeorm'; import { config } from '../../../config'; import { RunnerGroupNotFoundError } from '../../../errors/RunnerGroupErrors'; import { Address } from '../../entities/Address'; import { GroupContact } from '../../entities/GroupContact'; import { RunnerGroup } from '../../entities/RunnerGroup'; /** * This classed is used to create a new GroupContact entity from a json body (post request). */ export class CreateGroupContact { /** * The new contact's first name. */ @IsNotEmpty() @IsString() firstname: string; /** * The new contact's middle name. */ @IsOptional() @IsString() middlename?: string; /** * The new contact's last name. */ @IsNotEmpty() @IsString() lastname: string; /** * The new contact's address. */ @IsOptional() @IsObject() address?: Address; /** * The contact's phone number. * This will be validated against the configured country phone numer syntax (default: international). */ @IsOptional() @IsPhoneNumber(config.phone_validation_countrycode) phone?: string; /** * The new contact's email address. */ @IsOptional() @IsEmail() email?: string; /** * The new contacts's groups' ids. * You can provide either one groupId or an array of groupIDs. */ @IsOptional() groups?: number[] | number /** * Get's all groups for this contact by their id's; */ public async getGroups(): Promise { if (!this.groups) { return null; } let groups = new Array(); if (!Array.isArray(this.groups)) { this.groups = [this.groups] } for (let group of this.groups) { let found = await getConnectionManager().get().getRepository(RunnerGroup).findOne({ id: group }); if (!found) { throw new RunnerGroupNotFoundError(); } groups.push(found); } return groups; } /** * Creates a new GroupContact entity from this. */ public async toEntity(): Promise { let newContact: GroupContact = new GroupContact(); newContact.firstname = this.firstname; newContact.middlename = this.middlename; newContact.lastname = this.lastname; newContact.email = this.email; newContact.phone = this.phone; newContact.address = this.address; Address.validate(newContact.address); newContact.groups = await this.getGroups(); return newContact; } }