@bernierllc/file-handler
v0.2.3
Published
Unified file operations and storage abstraction for @bernierllc packages
Readme
@bernierllc/file-handler
Unified file operations and storage abstraction for @bernierllc packages. This core package provides a clean interface for file upload, download, processing, and validation across multiple storage backends.
Installation
npm install @bernierllc/file-handlerUsage
import { FileHandler, FileData } from '@bernierllc/file-handler';
// Initialize with configuration
const fileHandler = new FileHandler({
storage: {
type: 'supabase', // or 'auto', 's3', 'azure', 'gcp', 'local'
fallbackTo: ['local']
},
processing: {
imageOptimization: true,
validation: true,
maxFileSize: '10MB',
allowedTypes: ['image/*', 'application/pdf']
}
});
// Initialize the handler
await fileHandler.initialize();
// Upload a file
const fileData: FileData = {
buffer: fileBuffer,
filename: 'example.jpg',
contentType: 'image/jpeg',
size: fileBuffer.length
};
const uploadResult = await fileHandler.uploadFile(fileData, {
path: 'uploads',
public: true
});
if (uploadResult.success) {
console.log('File uploaded:', uploadResult.data.fileId);
}
// Download a file
const downloadResult = await fileHandler.downloadFile(fileId);
if (downloadResult.success) {
console.log('Downloaded file:', downloadResult.data.filename);
}
// Process an image
const processResult = await fileHandler.processImage(imageBuffer, {
resize: { width: 800, height: 600 },
format: 'webp',
quality: 85
});
// Validate a file
const validation = await fileHandler.validateFile(fileData, {
maxSize: 5 * 1024 * 1024, // 5MB
allowedTypes: ['image/*'],
allowedExtensions: ['jpg', 'png', 'webp']
});API Reference
FileHandler
Main class providing unified file operations.
Constructor
new FileHandler(config?: FileHandlerConfig)Methods
initialize(): Promise<FileOperationResult<void>>- Initialize the file handleruploadFile(file: FileData, options?: UploadOptions): Promise<FileOperationResult<UploadResult>>- Upload a filedownloadFile(fileId: string, options?: DownloadOptions): Promise<FileOperationResult<FileData>>- Download a filedeleteFile(fileId: string): Promise<FileOperationResult<DeleteResult>>- Delete a filelistFiles(options?: ListOptions): Promise<FileOperationResult<FileList>>- List filesgetFileMetadata(fileId: string): Promise<FileOperationResult<FileMetadata>>- Get file metadatagetFileUrl(fileId: string, expiresIn?: number): Promise<FileOperationResult<string>>- Get file URLprocessImage(buffer: Buffer, options: ImageProcessOptions): Promise<FileOperationResult<Buffer>>- Process an imagevalidateFile(file: FileData, rules?: ValidationRules): Promise<ValidationResult>- Validate a filescanForVirus(buffer: Buffer): Promise<ScanResult>- Scan file for viruses (placeholder)
Storage Backends
Supported Backends
- Supabase Storage - Full implementation with upload, download, delete, list operations
- Local Storage - Planned (not implemented)
- AWS S3 - Planned (not implemented)
- Azure Blob Storage - Planned (not implemented)
- Google Cloud Storage - Planned (not implemented)
Backend Selection
{
storage: {
type: 'auto', // Auto-select best available backend
fallbackTo: ['supabase', 'local'] // Fallback order
}
}Image Processing
Powered by Sharp for high-performance image transformations:
const processed = await ImageProcessor.processImage(buffer, {
resize: { width: 800, height: 600, fit: 'cover' },
format: 'webp',
quality: 85,
blur: 2,
sharpen: 1,
rotate: 90,
flip: 'horizontal'
});File Validation
Comprehensive security and constraint validation:
const validation = await FileValidator.validateFile(file, {
maxSize: 10 * 1024 * 1024, // 10MB
allowedTypes: ['image/*', 'application/pdf'],
allowedExtensions: ['jpg', 'png', 'pdf'],
maxDimensions: { width: 2000, height: 2000 }
});Security Features
- Executable file detection and blocking
- Directory traversal protection
- Suspicious filename pattern detection
- File type validation with MIME type checking
- Size limit enforcement
Configuration
Environment Variables
For Supabase backend:
SUPABASE_URL=your_supabase_url
SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_BUCKET_NAME=uploadsFileHandlerConfig
interface FileHandlerConfig {
storage?: {
type: 'auto' | 'local' | 's3' | 'azure' | 'gcp' | 'supabase';
fallbackTo?: string[];
};
processing?: {
imageOptimization?: boolean;
virusScanning?: boolean;
validation?: boolean;
maxFileSize?: string;
allowedTypes?: string[];
};
}Error Handling
All operations return FileOperationResult<T> with structured error handling:
interface FileOperationResult<T = void> {
success: boolean;
data?: T;
error?: string;
}See Also
- @bernierllc/retry-policy - Used for upload retry logic
- @bernierllc/csv-parser - CSV file processing
- @bernierllc/markdown-renderer - Markdown file processing
License
Copyright (c) 2025 Bernier LLC. All rights reserved.
