import {Injectable, Model, Field, FieldType, collect, Related, QueryRow} from '@extollo/lib' import {HostGroupHost} from './HostGroupHost.model' /** * HostGroup Model * ----------------------------------- * Put some description here. */ @Injectable() export class HostGroup extends Model { protected static table = 'p5x_host_groups' protected static key = 'id' @Field(FieldType.serial) public id?: number @Field(FieldType.varchar) public name!: string @Related() public hosts() { return this.hasMany(HostGroupHost, 'id', 'hostGroupId') } public async setHosts(pveHosts: string[]): Promise { if ( !this.id ) { throw new Error('Cannot setHosts on HostGroup that has not yet been persisted') } // Remove any existing hosts await this.hosts().query().delete() // Insert the host records const rows = pveHosts.map(pveHost => ({ pveHost, hostGroupId: this.key(), })) await HostGroupHost.query() .insert(rows) } public async toCobalt(): Promise { const obj = this.toQueryRow() obj.hosts = await this.hosts().get().then(x => x.pluck('pveHost')) return obj } }