import Inject, { RegisterScoped } from "@entity-access/entity-access/dist/di/di.js"; import TimeSpan from "@entity-access/entity-access/dist/types/TimeSpan.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import CacheService from "../cache/CacheService.js"; import FileConversionService from "./FileConversionService.js"; import { TempFileResult } from "@entity-access/server-pages/dist/Content.js"; import { CORS } from "../../../common/CORS.js"; interface ICacheParams { type: string; cacheKey: string; ttl?: TimeSpan; fileName: string; senderDomain: string; factory:() => Promise; } @RegisterScoped export default class CachedFileConversionService { @Inject cacheService: CacheService; @Inject fc: FileConversionService; async getOrCreateResult(p: ICacheParams, cors = true) { const ttl = p.ttl ??= TimeSpan.fromDays(30); const file = await this.getOrCreate(p); return new TempFileResult(file, { headers: { ... cors ? CORS.allowAll: {}, "cache-control": `public,max-age=${ Math.floor(ttl.totalSeconds)}` } }); } async getOrCreate(p: ICacheParams) { const { type, cacheKey, ttl = TimeSpan.fromDays(30) } = p; const key = `cached-files-2-${type}-${cacheKey}`; return await this.cacheService.get({ key, ttl, factory: (c) => this.getFile(p) }); } async getFile(p: ICacheParams) { if(/download|view/i.test(p.type)) { return await p.factory(); } const { senderDomain, fileName } = p; const originalFile = await this.getOrCreate({ ... p, type: "view" }); return await this.fc.transform(p.type, originalFile, { fileName, senderDomain }); } }