swaf/src/auth/models/UserEmail.ts

50 lines
1.5 KiB
TypeScript

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 readonly id?: number = undefined;
public user_id?: number = undefined;
public readonly email?: string = undefined;
private main?: boolean = undefined;
public created_at?: Date = undefined;
public readonly user = new OneModelRelation<UserEmail, User>(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 Boolean(this.main);
}
public setMain() {
if (!this.isMain()) {
this.main = true;
this._wasSetToMain = true;
}
}
}