import User from "./User"; import {Connection} from "mysql"; import Model, {EMAIL_REGEX, ModelCache} from "../../db/Model"; import Validator from "../../db/Validator"; import {query} from "../../db/MysqlConnectionManager"; export default class UserEmail extends Model { public static async fromEmail(email: any): Promise { const emails = await this.models(this.select().where('email', email).first()); return emails.length > 0 ? emails[0] : null; } public user_id?: number; public email?: string; private main?: boolean; public created_at?: Date; private wasSetToMain: boolean = false; constructor(data: any) { super(data); } protected defineProperties(): void { this.defineProperty('user_id', new Validator().acceptUndefined().exists(User, 'id')); this.defineProperty('email', new Validator().defined().regexp(EMAIL_REGEX).unique(this)); this.defineProperty('main', new Validator().defined()); this.defineProperty('created_at', new Validator()); } 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); } } protected async afterSave(): Promise { if (this.wasSetToMain) { this.wasSetToMain = false; const emails = ModelCache.all(this.table); if (emails) { for (const id in emails) { const otherEmail = emails[id]; if (otherEmail.id !== this.id && otherEmail.user_id === this.user_id) { otherEmail.main = false; } } } } } public isMain(): boolean { return !!this.main; } public setMain() { if (!this.isMain()) { this.main = true; this.wasSetToMain = true; } } }