import User from "./User"; import {Connection} from "mysql"; import Model, {EMAIL_REGEX} from "../../db/Model"; import {query} from "../../db/MysqlConnectionManager"; import {OneModelRelation} from "../../db/ModelRelation"; import ModelFactory from "../../db/ModelFactory"; export default class UserEmail extends Model { public user_id?: number; public readonly email!: string; private main!: boolean; public created_at?: Date; public readonly user = new OneModelRelation(this, ModelFactory.get(User), { localKey: 'user_id', foreignKey: 'id' }); private _wasSetToMain: boolean = false; constructor(data: any) { super(data); } protected init(): void { this.setValidation('user_id').acceptUndefined().exists(User, 'id'); this.setValidation('email').defined().regexp(EMAIL_REGEX).unique(this); this.setValidation('main').defined(); } protected async beforeSave(exists: boolean, connection: Connection) { if (this._wasSetToMain) { await query(`UPDATE ${this.table} SET main=false WHERE user_id=${this.user_id}`, null, connection); this._wasSetToMain = false; } } public isMain(): boolean { return this.main; } public setMain() { if (!this.isMain()) { this.main = true; this._wasSetToMain = true; } } }