diff --git a/src/models/actions/create/CreateGroupContact.ts b/src/models/actions/create/CreateGroupContact.ts index e261f51..8d7e0bd 100644 --- a/src/models/actions/create/CreateGroupContact.ts +++ b/src/models/actions/create/CreateGroupContact.ts @@ -1,7 +1,10 @@ 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 Group entity from a json body (post request). @@ -50,6 +53,30 @@ export class CreateGroupContact { @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 Address entity from this. @@ -63,6 +90,8 @@ export class CreateGroupContact { newContact.phone = this.phone; newContact.address = this.address; Address.validate(newContact.address); + newContact.groups = await this.getGroups(); + return newContact; } } \ No newline at end of file