ily.li/src/models/FileModel.ts

53 lines
1.9 KiB
TypeScript

import Model from "wms-core/db/Model";
import Validator from "wms-core/db/Validator";
import Controller from "wms-core/Controller";
import config from "config";
export default class FileModel extends Model {
public static get table(): string {
return 'files';
}
public static async getBySlug(slug: string): Promise<FileModel | null> {
const models = await this.models<FileModel>(this.select().where('slug', slug).first());
return models.length > 0 ? models[0] : null;
}
public readonly slug!: string;
public readonly real_name!: string;
public readonly storage_type!: FileStorage;
public readonly storage_path!: string;
public created_at?: Date;
public readonly ttl!: number;
protected defineProperties() {
this.defineProperty('slug', new Validator().defined().minLength(1).maxLength(259).unique(this, 'slug'));
this.defineProperty('real_name', new Validator().defined().minLength(1).maxLength(259));
this.defineProperty('storage_type', new Validator().defined().maxLength(64));
this.defineProperty('storage_path', new Validator().defined().maxLength(1745));
this.defineProperty('created_at', new Validator());
this.defineProperty('ttl', new Validator().defined().min(0).max(4294967295));
}
public getURL(): string {
return config.get<string>('base_url') + Controller.route('get-file', {
slug: this.slug,
});
}
public getExpirationDate(): Date | null {
if (!this.created_at) return new Date();
if (this.ttl === 0) return null;
return new Date(this.created_at.getTime() + this.ttl * 1000);
}
public shouldBeDeleted(): boolean {
const expirationDate = this.getExpirationDate();
if (!expirationDate) return false;
return new Date().getTime() >= expirationDate.getTime();
}
}
export type FileStorage = 'local';