Added firebase function to generate thumnails from uploaded images

This commit is contained in:
Mariano Uvalle 2019-04-07 18:06:21 -05:00
parent 8ce0441b12
commit 6865399151
3 changed files with 645 additions and 153 deletions

File diff suppressed because it is too large Load diff

View file

@ -11,8 +11,13 @@
}, },
"main": "lib/index.js", "main": "lib/index.js",
"dependencies": { "dependencies": {
"@google-cloud/storage": "^2.5.0",
"@types/fs-extra": "^5.0.5",
"@types/sharp": "^0.22.1",
"firebase-admin": "~7.0.0", "firebase-admin": "~7.0.0",
"firebase-functions": "^2.2.0" "firebase-functions": "^2.2.0",
"fs-extra": "^7.0.1",
"sharp": "^0.22.0"
}, },
"devDependencies": { "devDependencies": {
"tslint": "^5.12.0", "tslint": "^5.12.0",

View file

@ -1,8 +1,50 @@
import * as functions from 'firebase-functions'; import * as functions from 'firebase-functions';
import { Storage } from '@google-cloud/storage';
// // Start writing Firebase Functions const gcs = new Storage();
// // https://firebase.google.com/docs/functions/typescript
// import { tmpdir } from 'os';
// export const helloWorld = functions.https.onRequest((request, response) => { import { join, dirname } from 'path';
// response.send("Hello from Firebase!");
// }); import * as sharp from 'sharp';
import * as fs from 'fs-extra';
export const generateThumb = functions.storage.object().onFinalize(async object => {
// Find the bucket where the uploaded dile resides.
const bucket = gcs.bucket(object.bucket);
const filePathGcs = object.name;
const fileName = filePathGcs!.split('/').pop();
const bucketDirectory = dirname(filePathGcs!);
const workingDirectory = join(tmpdir(), 'thumbnails');
const tmpFilePath = join(workingDirectory, 'source.png');
if (fileName!.includes('thumb@') || !object.contentType!.includes('image')) {
console.log('Exiting function');
return false;
}
// Ensure that our directory exists.
await fs.ensureDir(workingDirectory);
// Download the source file to the temporary directory.
await bucket.file(filePathGcs!).download({
destination: tmpFilePath,
});
// Create the thumnail in 124 size.
const thumbnailName = `thumb@${fileName}`;
const thumbnailLocalPath = join(workingDirectory, thumbnailName);
await sharp(tmpFilePath)
.resize(124, 124)
.toFile(thumbnailLocalPath);
// Upload the resulting thumnail to the same directory as the original file.
await bucket.upload(thumbnailLocalPath, {
destination: join(bucketDirectory, thumbnailName),
});
// Exit the function deleting all the temprorary files.
return fs.remove(workingDirectory);
});