2020-11-22 13:49:08 +01:00
|
|
|
import Model from "swaf/db/Model";
|
|
|
|
import User from "swaf/auth/models/User";
|
2020-07-06 10:49:18 +02:00
|
|
|
import FileModel from "./FileModel";
|
|
|
|
import {Request} from "express";
|
|
|
|
import config from "config";
|
2020-11-22 13:49:08 +01:00
|
|
|
import Controller from "swaf/Controller";
|
2020-07-06 10:49:18 +02:00
|
|
|
|
|
|
|
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[]> {
|
2021-03-30 12:31:47 +02:00
|
|
|
req.params.sortBy = 'created_at';
|
|
|
|
req.params.sortDirection = 'DESC';
|
2020-07-06 10:49:18 +02:00
|
|
|
return await this.paginate(req, perPage, this.select().where('user_id', user_id));
|
|
|
|
}
|
|
|
|
|
2020-08-11 17:54:15 +02:00
|
|
|
public id?: number = undefined;
|
|
|
|
public readonly user_id?: number = undefined;
|
|
|
|
public readonly slug?: string = undefined;
|
|
|
|
public readonly target_url?: string = undefined;
|
|
|
|
public created_at?: Date = undefined;
|
2020-07-06 10:49:18 +02:00
|
|
|
|
|
|
|
protected init(): void {
|
2020-08-11 17:54:15 +02:00
|
|
|
this.setValidation('user_id').defined().exists(User, 'id');
|
2021-03-30 16:19:37 +02:00
|
|
|
this.setValidation('slug').defined().minLength(1).maxLength(259)
|
|
|
|
.unique(this, 'slug')
|
|
|
|
.unique(FileModel, 'slug');
|
2020-08-11 17:54:15 +02:00
|
|
|
this.setValidation('target_url').defined().maxLength(1745).regexp(/^https?:\/\/.{3,259}?\/?/i);
|
2020-07-06 10:49:18 +02:00
|
|
|
}
|
|
|
|
|
2021-01-26 14:27:55 +01:00
|
|
|
public getURL(domain: string = config.get<string>('public_url')): string {
|
2020-07-06 14:52:38 +02:00
|
|
|
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + Controller.route('get-url', {
|
2020-11-22 14:13:57 +01:00
|
|
|
slug: this.getOrFail('slug'),
|
2020-07-06 10:49:18 +02:00
|
|
|
});
|
|
|
|
}
|
2020-11-22 13:49:08 +01:00
|
|
|
}
|