ily.li/src/models/URLRedirect.ts

49 lines
1.7 KiB
TypeScript

import config from "config";
import {Request} from "express";
import User from "swaf/auth/models/User";
import {route} from "swaf/common/Routing";
import Model from "swaf/db/Model";
import {ModelQueryResult} from "swaf/db/ModelQuery";
import FileModel from "./FileModel.js";
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<ModelQueryResult<URLRedirect>> {
req.params.sortBy = 'created_at';
req.params.sortDirection = 'DESC';
return await this.paginate(req, perPage, this.select().where('user_id', user_id));
}
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;
protected init(): void {
this.setValidation('user_id').defined().exists(User, 'id');
this.setValidation('slug').defined().minLength(1).maxLength(259)
.unique(this, 'slug')
.unique(FileModel, 'slug');
this.setValidation('target_url').defined().maxLength(1745).regexp(/^https?:\/\/.{3,259}?\/?/i);
}
public getURL(domain: string = config.get<string>('public_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + route('get-url', {
slug: this.getOrFail('slug'),
});
}
}