import { MinioClient } from './minio.js'; import { NatsClient } from './nats.js'; import { FFmpegConverter } from './ffmpeg.js'; import { extname, parse } from 'path'; export class ImageDerivativesGenerator { minioClient; natsClient; ffmpegConverter; resolutions = [320, 640, 960, 1280, 1600, 1920]; formats = ['avif', 'webp', 'jpeg']; constructor(minioClient, natsClient, ffmpegConverter) { this.minioClient = minioClient; this.natsClient = natsClient; this.ffmpegConverter = ffmpegConverter; } async start() { console.log('šŸš€ Starting Image Derivatives Generator Service'); console.log(`šŸ“Š Resolutions: ${this.resolutions.join(', ')}`); console.log(`šŸŽØ Formats: ${this.formats.join(', ')}`); await this.natsClient.subscribe('generate-derivatives', async (message) => { console.log(message); await this.processMessage(message); }); console.log('āœ… Service ready'); } async processMessage(message) { const { s3ObjectKey } = message; console.log(`\nšŸ“„ Processing: ${s3ObjectKey}`); try { // Download original image from MinIO const originalBuffer = await this.minioClient.downloadFile(s3ObjectKey); console.log(` āœ“ Downloaded original (${(originalBuffer.length / 1024).toFixed(2)} KB)`); // Parse the original file path const parsedPath = parse(s3ObjectKey); const baseDir = parsedPath.dir; const baseName = parsedPath.name; let totalGenerated = 0; let totalSkipped = 0; // Generate all combinations of resolutions and formats for (const width of this.resolutions) { for (const format of this.formats) { const derivativeKey = `${baseDir}/${baseName}_${width}.${format}`; // Check if derivative already exists const exists = await this.minioClient.fileExists(derivativeKey); if (exists) { totalSkipped++; continue; } try { // Convert image const result = await this.ffmpegConverter.convert(originalBuffer, { width, format, }); // Upload to MinIO const contentType = this.ffmpegConverter.getContentType(format); await this.minioClient.uploadFile(derivativeKey, result.buffer, contentType); totalGenerated++; console.log(` āœ“ Generated ${width}w ${format} (${(result.buffer.length / 1024).toFixed(2)} KB)`); } catch (error) { console.error(` āœ— Failed to generate ${width}w ${format}:`, error instanceof Error ? error.message : error); } } } console.log(`\nāœ… Completed: ${totalGenerated} generated, ${totalSkipped} skipped for ${s3ObjectKey}`); } catch (error) { console.error(`āŒ Error processing ${s3ObjectKey}:`, error); } } async stop() { console.log('\nšŸ›‘ Stopping service...'); await this.natsClient.close(); console.log('āœ“ Service stopped'); } } //# sourceMappingURL=image-derivatives-generator.js.map