rainbox.email/src/models/MailDomain.ts

45 lines
1.6 KiB
TypeScript

import Model from "swaf/db/Model";
import User from "swaf/auth/models/User";
import {ManyModelRelation, OneModelRelation} from "swaf/db/ModelRelation";
import MailIdentity from "./MailIdentity";
import UserNameComponent from "swaf/auth/models/UserNameComponent";
export default class MailDomain extends Model {
public id?: number = undefined;
public name?: string = undefined;
public user_id?: number | null = undefined;
public readonly owner: OneModelRelation<MailDomain, User> = new OneModelRelation(this, User, {
localKey: 'user_id',
foreignKey: 'id',
});
public readonly identities: ManyModelRelation<MailDomain, MailIdentity> = new ManyModelRelation(this, MailIdentity,
{
localKey: 'id',
foreignKey: 'mail_domain_id',
});
public updateWithData(data: Pick<this, keyof this> | Record<string, unknown>): void {
super.updateWithData(data);
if (this.user_id !== null && this.user_id !== undefined && this.user_id <= 0) this.user_id = null;
}
protected init(): void {
this.setValidation('name').acceptUndefined()
.maxLength(252)
.regexp(/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/)
.unique(this);
this.setValidation('user_id').acceptUndefined().exists(User, 'id');
}
public isPublic(): boolean {
return !this.user_id;
}
public canCreateAddresses(user: User): boolean {
return this.user_id === user.id || this.isPublic() && user.as(UserNameComponent).hasName();
}
}