import BaseStorage from "../BaseStorage.js"; import path from "path"; import { unlink, writeFile } from "fs/promises"; import { createReadStream, existsSync, mkdirSync } from "fs"; import sleep from "../../../common/sleep.js"; import ensureDir, { ensureParentFolder } from "../../../common/FileApi.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; export default class VolumeStorage extends BaseStorage { constructor(private root: string) { super(); ensureDir(root); } verify(): Promise { if(!existsSync(this.root)) { mkdirSync(this.root, { recursive: true }); } return Promise.resolve(); } async createFile(cloudPath: string, file: LocalFile) { const filePath = this.toFilePath(cloudPath, true); await writeFile(filePath, file.openRead() as any); return cloudPath; } async deleteFile(cloudPath: string) { const filePath = this.toFilePath(cloudPath); if (!existsSync(filePath)) { return; } await unlink(filePath); } async streamFile(cloudPath: string) { await sleep(1); const filePath = this.toFilePath(cloudPath); if (!existsSync(filePath)) { throw new Error("File does not exist"); } return { contentType: "", stream: createReadStream(filePath)}; } private toFilePath(cloudPath: string, create = false) { const filePath = path.join(this.root, cloudPath); if (create) { ensureParentFolder(filePath); } return filePath; } }