-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
58 lines (46 loc) · 1.94 KB
/
Copy pathindex.js
File metadata and controls
58 lines (46 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const functions = require('@google-cloud/functions-framework');
const { Storage } = require('@google-cloud/storage');
const sharp = require('sharp');
const path = require('path');
const storage = new Storage();
// Register a CloudEvent callback
functions.cloudEvent('generateThumbnail', async (cloudEvent) => {
try {
// Extract file data from the CloudEvent
const fileData = cloudEvent.data;
const bucketName = fileData.bucket;
const filePath = fileData.name; // e.g., "images/photo.jpg"
console.log("file data:",fileData);
// 1. Exit if it's not an image
if (!filePath.startsWith('images/')) {
console.log(`Skipping non-image file: ${filePath}`);
return;
}
// 2. Exit if it's already a thumbnail (Avoid Infinite Loop!)
if (path.basename(filePath).startsWith('thumbnails')) {
console.log('Already a thumbnail, skipping.');
return;
}
console.log(`Processing file: ${filePath} from bucket: ${bucketName}`);
// Download, resize, and upload logic goes here...
const bucket = storage.bucket(bucketName);
const [content] = await bucket.file(filePath).download();
const fileName = path.basename(filePath);
const [thumbnail, optimised] = await Promise.all([
sharp(content).resize(400, null).toBuffer(),
sharp(content).resize(800, null).toBuffer(),
]);
const thumbPath = `thumbnails/${fileName}`;
const optimisedPath = `optimised/${fileName}`;
await Promise.all([
bucket.file(thumbPath).save(thumbnail),
bucket.file(optimisedPath).save(optimised),
]);
console.log(`Thumbnail uploaded to ${thumbPath}`);
console.log(`Optimised image uploaded to ${optimisedPath}`);
} catch (error) {
console.error(`Error processing file: ${error.message}`, error);
// Don't rethrow - this tells Cloud Run the event was processed
// preventing automatic retries
}
});