2020-04-24 12:12:27 +02:00
|
|
|
import User from "./User";
|
|
|
|
import {Connection} from "mysql";
|
2020-06-27 14:36:50 +02:00
|
|
|
import Model, {EMAIL_REGEX} from "../../db/Model";
|
2020-04-24 12:12:27 +02:00
|
|
|
import {query} from "../../db/MysqlConnectionManager";
|
2020-06-27 14:36:50 +02:00
|
|
|
import {OneModelRelation} from "../../db/ModelRelation";
|
2020-07-24 12:13:28 +02:00
|
|
|
import ModelFactory from "../../db/ModelFactory";
|
2020-04-24 12:12:27 +02:00
|
|
|
|
|
|
|
export default class UserEmail extends Model {
|
2020-07-24 15:40:10 +02:00
|
|
|
public readonly id?: number = undefined;
|
|
|
|
public user_id?: number = undefined;
|
|
|
|
public readonly email?: string = undefined;
|
|
|
|
private main?: boolean = undefined;
|
|
|
|
public created_at?: Date = undefined;
|
2020-04-24 12:12:27 +02:00
|
|
|
|
2020-07-24 12:13:28 +02:00
|
|
|
public readonly user = new OneModelRelation<UserEmail, User>(this, ModelFactory.get(User), {
|
2020-06-27 14:36:50 +02:00
|
|
|
localKey: 'user_id',
|
|
|
|
foreignKey: 'id'
|
|
|
|
});
|
|
|
|
|
2020-07-24 12:13:28 +02:00
|
|
|
private _wasSetToMain: boolean = false;
|
2020-04-24 12:12:27 +02:00
|
|
|
|
|
|
|
constructor(data: any) {
|
|
|
|
super(data);
|
|
|
|
}
|
|
|
|
|
2020-06-27 14:36:50 +02:00
|
|
|
protected init(): void {
|
2020-07-24 12:13:28 +02:00
|
|
|
this.setValidation('user_id').acceptUndefined().exists(User, 'id');
|
|
|
|
this.setValidation('email').defined().regexp(EMAIL_REGEX).unique(this);
|
|
|
|
this.setValidation('main').defined();
|
2020-04-24 12:12:27 +02:00
|
|
|
}
|
|
|
|
|
2020-07-24 12:13:28 +02:00
|
|
|
protected async beforeSave(exists: boolean, connection: Connection) {
|
|
|
|
if (this._wasSetToMain) {
|
2020-04-24 12:12:27 +02:00
|
|
|
await query(`UPDATE ${this.table} SET main=false WHERE user_id=${this.user_id}`, null, connection);
|
2020-07-24 12:13:28 +02:00
|
|
|
this._wasSetToMain = false;
|
2020-04-24 12:12:27 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public isMain(): boolean {
|
2020-07-24 15:40:10 +02:00
|
|
|
return Boolean(this.main);
|
2020-04-24 12:12:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public setMain() {
|
|
|
|
if (!this.isMain()) {
|
|
|
|
this.main = true;
|
2020-07-24 12:13:28 +02:00
|
|
|
this._wasSetToMain = true;
|
2020-04-24 12:12:27 +02:00
|
|
|
}
|
|
|
|
}
|
2020-07-24 12:13:28 +02:00
|
|
|
}
|