Skip to content

Instantly share code, notes, and snippets.

@nilsmehlhorn
Last active March 20, 2022 00:31
Show Gist options
  • Save nilsmehlhorn/782d745fcf68824c3ec560cda17c4eb8 to your computer and use it in GitHub Desktop.
Save nilsmehlhorn/782d745fcf68824c3ec560cda17c4eb8 to your computer and use it in GitHub Desktop.
Firebase Cloud Function: Thumbnail Generator (Serverless)
const { join, dirname } = require('path')
const sharp = require('sharp')
const { Storage } = require('@google-cloud/storage')
const { promisify } = require('util')
const pump = promisify(require('pump'))
const gcs = new Storage()
const SIZE = 128
const PREFIX = 'thumb@'
exports.generateThumbs = event => {
const filePath = event.name
const fileName = filePath.split('/').pop()
if (fileName.startsWith(PREFIX) || !event.contentType.includes('image')) {
return
}
const bucket = gcs.bucket(event.bucket)
const imgIn = bucket.file(filePath).createReadStream()
const resizer = sharp().resize(SIZE, SIZE)
const thumbOut = bucket.file(join(dirname(filePath), `${PREFIX}${fileName}`)).createWriteStream({
contentType: event.contentType,
resumable: false
})
return pump(imgIn, resizer, thumbOut)
}
{
"name": "thumberator",
"version": "0.1.0",
"main": "index.js",
"scripts": {
"deploy": "serverless deploy",
"deploy:prod": "serverless deploy --stage prod"
},
"devDependencies": {
"serverless": "^1.41.1",
"serverless-google-cloudfunctions": "^2.3.2"
},
"dependencies": {
"@google-cloud/storage": "^2.5.0",
"pump": "^3.0.0",
"sharp": "^0.22.1"
}
}
service: thumberator
custom:
stages:
- dev
- prod
buckets:
dev: <dev-bucket>
prod: <prod-bucket>
provider:
name: google
runtime: nodejs8
region: <region>
stage: ${opt:stage,'dev'}
project: <firebase-project>
credentials: <path-to-service-json>
plugins:
- serverless-google-cloudfunctions
package:
exclude:
- node_modules/**
- .gitignore
- .git/**
functions:
generateThumbs:
handler: generateThumbs
events:
- event:
eventType: google.storage.object.finalize
resource: projects/<firebase-project>/buckets/${self:custom.buckets.${self:provider.stage}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment