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 Validator from "../../db/Validator";
|
|
|
|
import {query} from "../../db/MysqlConnectionManager";
|
2020-06-27 14:36:50 +02:00
|
|
|
import {OneModelRelation} from "../../db/ModelRelation";
|
2020-04-24 12:12:27 +02:00
|
|
|
|
|
|
|
export default class UserEmail extends Model {
|
|
|
|
public user_id?: number;
|
2020-06-14 11:41:44 +02:00
|
|
|
public readonly email!: string;
|
|
|
|
private main!: boolean;
|
2020-04-24 12:12:27 +02:00
|
|
|
public created_at?: Date;
|
|
|
|
|
2020-06-27 14:36:50 +02:00
|
|
|
public readonly user = new OneModelRelation<this, User>(this, User, {
|
|
|
|
localKey: 'user_id',
|
|
|
|
foreignKey: 'id'
|
|
|
|
});
|
|
|
|
|
2020-04-24 12:12:27 +02:00
|
|
|
private wasSetToMain: boolean = false;
|
|
|
|
|
|
|
|
constructor(data: any) {
|
|
|
|
super(data);
|
|
|
|
}
|
|
|
|
|
2020-06-27 14:36:50 +02:00
|
|
|
protected init(): void {
|
|
|
|
this.addProperty<number>('user_id', new Validator().acceptUndefined().exists(User, 'id'));
|
|
|
|
this.addProperty<string>('email', new Validator().defined().regexp(EMAIL_REGEX).unique(this));
|
|
|
|
this.addProperty<boolean>('main', new Validator().defined());
|
|
|
|
this.addProperty<Date>('created_at', new Validator());
|
2020-04-24 12:12:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
2020-06-27 14:36:50 +02:00
|
|
|
return this.main;
|
2020-04-24 12:12:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public setMain() {
|
|
|
|
if (!this.isMain()) {
|
|
|
|
this.main = true;
|
|
|
|
this.wasSetToMain = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|