import * as plugins from './smartbucket.plugins.js'; import { Directory } from './smartbucket.classes.directory.js'; export interface IFileMetaData { name: string; fileType: string; size: string; } /** * represents a file in a directory */ export class File { // STATIC /** * creates a file in draft mode * you need to call .save() to store it in s3 * @param optionsArg */ public static async create(optionsArg: { directory: Directory; name: string; contents: Buffer | string | plugins.stream.Readable; /** * if contents are of type string, you can specify the encoding here */ encoding?: 'utf8' | 'binary'; }): Promise { const contents = typeof optionsArg.contents === 'string' ? Buffer.from(optionsArg.contents, optionsArg.encoding) : optionsArg.contents; const file = new File({ directoryRefArg: optionsArg.directory, fileName: optionsArg.name, }); if (contents instanceof plugins.stream.Readable) {} else { await optionsArg.directory.fastPut({ path: optionsArg.name, contents: contents, }); } return file; } // INSTANCE public parentDirectoryRef: Directory; public name: string; public path: string; public metaData: IFileMetaData; constructor(optionsArg: { directoryRefArg: Directory; fileName: string }) { this.parentDirectoryRef = optionsArg.directoryRefArg; this.name = optionsArg.fileName; } public async getContentAsString() { const fileBuffer = await this.getContentAsBuffer(); return fileBuffer.toString(); } public async getContentAsBuffer() { const done = plugins.smartpromise.defer(); const fileStream = await this.parentDirectoryRef.bucketRef.smartbucketRef.minioClient .getObject(this.parentDirectoryRef.bucketRef.name, this.path) .catch((e) => console.log(e)); let completeFile = Buffer.from(''); const duplexStream = new plugins.smartstream.SmartDuplex( { writeFunction: async (chunk) => { completeFile = Buffer.concat([chunk]); return chunk; }, finalFunction: async (cb) => { done.resolve(); return Buffer.from(''); }, } ); if (!fileStream) { return null; } fileStream.pipe(duplexStream); await done.promise; return completeFile; } public async readStreaming() { // TODO throw new Error('not yet implemented'); } /** * removes this file */ public async remove() { await this.parentDirectoryRef.bucketRef.smartbucketRef.minioClient.removeObject( this.parentDirectoryRef.bucketRef.name, this.path ); await this.parentDirectoryRef.listFiles(); } /** * deletes the file */ public async delete() {} /** * allows locking the file * @param optionsArg */ public async lock(optionsArg?: { timeoutMillis?: number }) {} /** * actively unlocks a file * */ public async unlock(optionsArg?: { /** * unlock the file even if not locked from this instance */ force?: boolean; }) {} public async updateWithContents(optionsArg: { contents: Buffer | string | plugins.stream.Readable; encoding?: 'utf8' | 'binary'; }) {} /** * allows updating the metadata of a file * @param updatedMetadata */ public async updateMetaData(updatedMetadata: any) {} }