ily.li/src/models/URLRedirect.ts

44 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-07-06 10:49:18 +02:00
import Model from "wms-core/db/Model";
import Validator from "wms-core/db/Validator";
import User from "wms-core/auth/models/User";
import FileModel from "./FileModel";
import {Request} from "express";
import config from "config";
import Controller from "wms-core/Controller";
export default class URLRedirect extends Model {
public static get table(): string {
return 'url_redirects';
}
public static async getBySlug(slug: string): Promise<URLRedirect | null> {
return await this.select().where('slug', slug).first();
}
public static async paginateForUser(req: Request, perPage: number, user_id: number): Promise<URLRedirect[]> {
return await this.paginate(req, perPage, this.select().where('user_id', user_id));
}
public readonly user_id!: number;
public readonly slug!: string;
public readonly target_url!: string;
public created_at?: Date;
constructor(data: any) {
super(data);
}
protected init(): void {
this.addProperty('user_id', new Validator().defined().exists(User, 'id'));
this.addProperty('slug', new Validator().defined().minLength(1).maxLength(259).unique(URLRedirect, 'slug').unique(FileModel, 'slug'));
this.addProperty('target_url', new Validator().defined().maxLength(1745).regexp(/^https?:\/\/.{3,259}?\/?/i));
this.addProperty('created_at', new Validator());
}
public getURL(domain: string = config.get<string>('base_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + Controller.route('get-url', {
2020-07-06 10:49:18 +02:00
slug: this.slug,
});
}
}