import User from "./User"; import {Connection} from "mysql"; import Model, {EMAIL_REGEX} from "../../db/Model"; import Validator from "../../db/Validator"; import {query} from "../../db/MysqlConnectionManager"; import {OneModelRelation} from "../../db/ModelRelation"; 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, User, { localKey: 'user_id', foreignKey: 'id' }); private wasSetToMain: boolean = false; constructor(data: any) { super(data); } protected init(): void { this.addProperty('user_id', new Validator().acceptUndefined().exists(User, 'id')); this.addProperty('email', new Validator().defined().regexp(EMAIL_REGEX).unique(this)); this.addProperty('main', new Validator().defined()); this.addProperty('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); this.wasSetToMain = false; } } public isMain(): boolean { return this.main; } public setMain() { if (!this.isMain()) { this.main = true; this.wasSetToMain = true; } } }