swaf/src/auth/models/UserEmail.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-04-24 12:12:27 +02:00
import User from "./User";
import {Connection} from "mysql";
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";
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;
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);
}
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 {
return this.main;
2020-04-24 12:12:27 +02:00
}
public setMain() {
if (!this.isMain()) {
this.main = true;
this.wasSetToMain = true;
}
}
}