Add readstream

This commit is contained in:
Philipinho
2025-05-21 10:58:40 -07:00
parent 625bdc7024
commit f6e3230eec
4 changed files with 35 additions and 0 deletions

View File

@ -5,6 +5,8 @@ import {
} from '../interfaces';
import { join } from 'path';
import * as fs from 'fs-extra';
import { Readable } from 'stream';
import { createReadStream } from 'node:fs';
export class LocalDriver implements StorageDriver {
private readonly config: LocalStorageConfig;
@ -43,6 +45,14 @@ export class LocalDriver implements StorageDriver {
}
}
async readStream(filePath: string): Promise<Readable> {
try {
return createReadStream(this._fullPath(filePath));
} catch (err) {
throw new Error(`Failed to read file: ${(err as Error).message}`);
}
}
async exists(filePath: string): Promise<boolean> {
try {
return await fs.pathExists(this._fullPath(filePath));

View File

@ -71,6 +71,21 @@ export class S3Driver implements StorageDriver {
}
}
async readStream(filePath: string): Promise<Readable> {
try {
const command = new GetObjectCommand({
Bucket: this.config.bucket,
Key: filePath,
});
const response = await this.s3Client.send(command);
return response.Body as Readable;
} catch (err) {
throw new Error(`Failed to read file from S3: ${(err as Error).message}`);
}
}
async exists(filePath: string): Promise<boolean> {
try {
const command = new HeadObjectCommand({

View File

@ -1,3 +1,5 @@
import { Readable } from 'stream';
export interface StorageDriver {
upload(filePath: string, file: Buffer): Promise<void>;
@ -5,6 +7,9 @@ export interface StorageDriver {
read(filePath: string): Promise<Buffer>;
readStream(filePath: string): Promise<Readable>;
exists(filePath: string): Promise<boolean>;
getUrl(filePath: string): string;

View File

@ -1,6 +1,7 @@
import { Inject, Injectable, Logger } from '@nestjs/common';
import { STORAGE_DRIVER_TOKEN } from './constants/storage.constants';
import { StorageDriver } from './interfaces';
import { Readable } from 'stream';
@Injectable()
export class StorageService {
@ -23,6 +24,10 @@ export class StorageService {
return this.storageDriver.read(filePath);
}
async readStream(filePath: string): Promise<Readable> {
return this.storageDriver.readStream(filePath);
}
async exists(filePath: string): Promise<boolean> {
return this.storageDriver.exists(filePath);
}