Created
August 8, 2023 16:57
-
-
Save jauntybrain/7fdb8d2accd25bef0ec54bf88a45b203 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as functions from "firebase-functions"; | |
import * as admin from "firebase-admin"; | |
import * as fs from "fs"; | |
import * as path from 'path'; | |
const app = admin.initializeApp(); | |
const firestore = admin.firestore(app); | |
exports.post = functions.https.onRequest(async (req, res) => { | |
// Get post ID from url params | |
const params = req.url.split('/'); | |
const postID = params[params.length - 1].trim(); | |
if (!postID) { | |
res.status(404).send('Post not found.'); | |
} | |
// Get the post snapshot from Firestore | |
const postSnapshot = await firestore.doc(`posts/${postID}`).get(); | |
// Check if the post exists | |
if (!postSnapshot.exists) { | |
res.status(404).send('Post not found.'); | |
return; | |
} | |
// Extract the data from the post | |
const postData = postSnapshot.data()!; | |
const operations = [{ | |
// Pass image from Cloud Storage | |
operation: 'input', | |
type: 'gcs', | |
source: postData.imagePath | |
}, | |
{ | |
// Resize to the common thumbnail size | |
operation: 'resize', | |
width: '1200', | |
height: '630', | |
fit: 'cover' | |
}, | |
{ | |
// Add title text | |
operation: 'text', | |
value: postData.title.toUpperCase(), | |
font: '900 70px sans-serif', | |
strokeWidth: 1, | |
maxWidth: 1000, | |
wrap: true, | |
left: 50, | |
top: 450, | |
}, | |
{ | |
// Add subtitle text | |
operation: 'text', | |
value: postData.subtitle, | |
font: '400 40px sans-serif', | |
maxWidth: 1000, | |
textColor: '#ffffffcc', | |
wrap: true, | |
left: 50, | |
top: 520, | |
}, | |
{ | |
// Output as JPG, reduce quality | |
operation: 'output', | |
quality: 80, | |
format: 'jpeg' | |
}, | |
]; | |
// Encode query parameters from operations and pass it to the Cloud Function | |
const encodedOperations = encodeURIComponent(JSON.stringify(operations)); | |
return `https://{FUNCTIONS_REGION}-{PROJECT_ID}.cloudfunctions.net/ext-image-processing-api-handler/process?operations=${encodedOperations}`; | |
// Return HTML file with metadata variables | |
const templatePath = path.join(__dirname, './assets/html/post.html'); | |
var source = fs.readFileSync(templatePath, { encoding: 'utf-8' }) | |
.replaceAll('{{title}}', postData.title) | |
.replaceAll('{{subtitle}}', postData.subtitle) | |
.replaceAll('{{imageUrl}}', imageUrl); | |
res.status(200).send(source); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment