import { PutObjectCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3"; // @see https://www.backblaze.com/docs/cloud-storage-use-the-aws-sdk-for-javascript-v3-with-backblaze-b2 import { readFile } from 'fs/promises'; import { env } from '../config/env' // adjust this path based on your project structure import logger from "./logger"; import { getNanoSpawn } from "./nanoSpawn"; let client: S3Client | null = null export async function uploadFile( s3Client: S3Client, bucket: string, key: string, filePath: string, mimetype: string ): Promise { if (!s3Client) throw new Error('uploadFile requires s3Client as first param'); if (!bucket) throw new Error('uploadFile requires bucket as second param'); if (!key) throw new Error('uploadFile requires key as third param'); if (!filePath) throw new Error('uploadFile requires filePath as fourth param'); if (!mimetype) throw new Error('uploadFile requires mimetype as fifth param'); logger.debug(`[uploadFile] filePath=${filePath} with key=${key} bucket=${bucket}`); const spawn = await getNanoSpawn(); await spawn('b2', ['file', 'upload', bucket, filePath, key]) return key // try { // // Read file content from disk // const fileBuffer = await readFile(filePath); // // Upload to S3 // await s3Client.send( // new PutObjectCommand({ // Bucket: bucket, // Key: key, // Body: fileBuffer, // ContentType: mimetype, // or determine dynamically if needed // }), // ); // return key; // } catch (caught) { // if (caught instanceof S3ServiceException) { // logger.error( // `Error from S3 while uploading to ${bucket}. ${caught.name}: ${caught.message}`, // ); // } else { // logger.error(`Unexpected error during upload:`, caught); // } // throw new Error(`Failed to upload ${filePath} to s3://${bucket}/${key}`); // } } export function getS3Client(): S3Client { if (!client) { client = new S3Client({ region: env.S3_REGION, endpoint: env.S3_ENDPOINT, credentials: { accessKeyId: env.S3_KEY_ID, secretAccessKey: env.S3_APPLICATION_KEY, }, forcePathStyle: env.S3_FORCE_PATH_STYLE, }) } return client }