smartbucket/ts/smartbucket.classes.file.ts
2019-10-18 15:43:06 +02:00

94 lines
2.4 KiB
TypeScript

import * as plugins from './smartbucket.plugins';
import { Directory } from './smartbucket.classes.directory';
export interface IFileMetaData {
name: string;
fileType: string;
size: string;
}
export class File {
// STATIC
public static async createFileFromString(
dirArg: Directory,
fileName: string,
fileContent: string
) {
await this.createFileFromBuffer(dirArg, fileName, Buffer.from(fileContent));
}
public static async createFileFromBuffer(
directoryRef: Directory,
fileName: string,
fileContent: Buffer
) {
const filePath = plugins.path.join(directoryRef.getBasePath(), fileName);
const streamIntake = new plugins.streamfunction.Intake();
const putPromise = directoryRef.bucketRef.smartbucketRef.minioClient
.putObject(this.name, filePath, streamIntake.getReadable())
.catch(e => console.log(e));
streamIntake.pushData(fileContent);
streamIntake.signalEnd();
await putPromise;
}
// INSTANCE
public parentDirectoryRef: Directory;
public name: string;
public path: string;
public metaData: IFileMetaData;
constructor(directoryRefArg: Directory, fileName: string) {
this.parentDirectoryRef = directoryRefArg;
this.name = 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 = new Buffer('');
const duplexStream = plugins.streamfunction.createDuplexStream<Buffer, Buffer>(
async chunk => {
completeFile = Buffer.concat([chunk]);
return chunk;
},
async cb => {
done.resolve();
return Buffer.from('');
}
);
if (!fileStream) {
return null;
}
fileStream.pipe(duplexStream);
await done.promise;
return completeFile;
}
public async streamContent() {
throw new Error('not yet implemented');
// TODO
}
/**
* removes this file
*/
public async remove() {
await this.parentDirectoryRef.bucketRef.smartbucketRef.minioClient.removeObject(
this.parentDirectoryRef.bucketRef.name,
this.path
);
await this.parentDirectoryRef.listFiles();
}
}