How you can use Firebase Cloud Functions to add server-side logic to a mobile application
- Get link
- X
- Other Apps
How you can use Firebase Cloud Functions to add server-side logic to a mobile application
1. User Authentication Triggers
Cloud Functions can be used to execute code in response to user authentication events, such as user creation or deletion.
Example: Send a Welcome Email on User Signup
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => {
const email = user.email; // The email of the user.
const displayName = user.displayName; // The display name of the user.
// Implement your email sending logic here.
console.log(`Sending welcome email to ${email}`);
});
2. Database Triggers
Cloud Functions can respond to changes in the Firebase Realtime Database or Firestore.
Example: Update User Count on New User Addition
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.updateUserCount = functions.firestore
.document('users/{userId}')
.onCreate((snap, context) => {
const newValue = snap.data();
const countRef = admin.firestore().collection('metrics').doc('userCount');
return countRef.update({
count: admin.firestore.FieldValue.increment(1)
});
});
3. HTTP Triggers
Cloud Functions can be exposed as HTTP endpoints that can be called directly from your mobile app.
Example: Create a Cloud Function to Handle HTTP Requests
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest((req, res) => {
const original = req.query.text;
admin.firestore().collection('messages').add({original: original}).then((writeResult) => {
res.json({result: `Message with ID: ${writeResult.id} added.`});
});
});
4. Scheduled Functions
You can schedule Cloud Functions to run at specific intervals, similar to a cron job.
Example: Clean Up Old Data Periodically
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.scheduledFunction = functions.pubsub.schedule('every 24 hours').onRun((context) => {
const now = admin.firestore.Timestamp.now();
const cutoff = new Date(now.toDate());
cutoff.setDate(cutoff.getDate() - 30); // 30 days ago
const cutoffTimestamp = admin.firestore.Timestamp.fromDate(cutoff);
const oldItemsQuery = admin.firestore().collection('items').where('createdAt', '<', cutoffTimestamp);
return oldItemsQuery.get().then((snapshot) => {
const batch = admin.firestore().batch();
snapshot.forEach((doc) => {
batch.delete(doc.ref);
});
return batch.commit();
});
});
5. Image Processing
You can use Cloud Functions to handle image uploads and perform processing tasks like resizing or generating thumbnails.
Example: Generate Thumbnails for Uploaded Images
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {Storage} = require('@google-cloud/storage');
const sharp = require('sharp');
admin.initializeApp();
const gcs = new Storage();
exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {
const bucket = gcs.bucket(object.bucket);
const filePath = object.name;
const fileName = filePath.split('/').pop();
const tempFilePath = `/tmp/${fileName}`;
const tempThumbnailPath = `/tmp/thumb_${fileName}`;
// Download the file from bucket.
await bucket.file(filePath).download({destination: tempFilePath});
// Generate a thumbnail using Sharp.
await sharp(tempFilePath).resize({width: 200}).toFile(tempThumbnailPath);
// Upload the thumbnail back to the bucket.
await bucket.upload(tempThumbnailPath, {
destination: `thumbnails/thumb_${fileName}`
});
});
These examples illustrate how you can leverage Firebase Cloud Functions to add powerful backend capabilities to your mobile applications without having to manage your own servers.
Comments
Post a Comment
What is your thought about this?