powr-sdk-api
Version:
Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.
53 lines (52 loc) • 1.51 kB
JavaScript
;
const {
Storage
} = require('@google-cloud/storage');
const {
format
} = require('date-fns');
const {
config,
credentials
} = require('../config');
const storage = new Storage({
projectId: config.projectId,
credentials: credentials
});
const bucketName = config.storageBucket;
const bucket = storage.bucket(bucketName);
console.log('Bucket:', bucketName);
console.log('Bucket:', bucket);
async function uploadToGCS(file) {
const timestamp = format(new Date(), 'yyyyMMdd-HHmmss');
const cleanFileName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '-');
const filename = `${timestamp}-${cleanFileName}`;
const blob = bucket.file(filename);
try {
console.log('Preparing to upload file:', {
name: file.originalname,
type: file.mimetype
});
const buffer = file.buffer;
console.log('Uploading file to GCS...');
await blob.save(buffer, {
contentType: file.mimetype,
metadata: {
contentType: file.mimetype
}
});
await blob.makePublic();
console.log('File made public successfully');
const publicUrl = `https://storage.googleapis.com/${bucketName}/${filename}`;
console.log('File uploaded and public URL generated:', publicUrl);
return publicUrl;
} catch (error) {
console.error('Error uploading file to GCS:', error);
throw new Error(`Failed to upload file to GCS: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
module.exports = {
uploadToGCS,
bucket,
bucketName
};