Use cases of Cloud Functions in real world scenarios

Tutorial 3 of 5

1. Introduction

This tutorial aims to explore the real-world use cases of Cloud Functions. Cloud Functions are small pieces of code that are triggered by specific events. They are serverless and fully managed, meaning you don't have to worry about managing any server infrastructure.

By the end of this tutorial, you'll have a clear understanding of how Cloud Functions can be used in various scenarios, from automated tasks like email notifications to complex systems like processing images or even handling IoT data.

To follow this tutorial, you'll need basic knowledge of JavaScript, as Google Cloud Functions primarily use Node.js.

2. Step-by-Step Guide

Cloud Functions are event-driven, meaning they execute in response to an event and the associated data. These events can be changes to data in a Firebase Realtime Database, new files uploaded to a Cloud Storage bucket, or an incoming HTTP request.

Cloud Functions are incredibly versatile and can be used in a variety of ways. Here are a few use cases:

  • Microservices: Cloud Functions can be used to create loosely coupled microservices.

  • Real-Time File Processing: They can be triggered by Cloud Storage events to process files as soon as they are uploaded.

  • Real-Time Analytics and Notifications: Cloud Functions can respond to changes in real-time data to provide live updates or notifications.

  • Serverless Backends: They can be used to build serverless backends for mobile, web, and IoT applications.

3. Code Examples

Below are some practical examples of Cloud Functions.

Example 1: Sending Welcome Emails

This function will send a welcome email to a new user when they sign up.

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');

//configure mail transporter service
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});

exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => {
  const email = user.email; // the email of the user
  const displayName = user.displayName; // the user's name

  return sendWelcomeEmail(email, displayName);
});

// Sends a welcome email to the given user.
function sendWelcomeEmail(email, displayName) {
  const mailOptions = {
    from: '"Spammy Corp." <noreply@spammycorp.com>',
    to: email
  };

  // the email body.
  mailOptions.subject = `Welcome to Spammy Corp., ${displayName}!`;
  mailOptions.text = `Hey ${displayName || ''}! Welcome to Spammy Corp. We hope you will enjoy our service.`;
  return mailTransport.sendMail(mailOptions).then(() => {
    return console.log('New welcome email sent to:', email);
  });
}

Example 2: Real-Time Image Processing

This is a more complex example where we resize an image when it's uploaded to a Cloud Storage bucket.

const functions = require('firebase-functions');
const sharp = require('sharp');
const path = require('path');
const os = require('os');
const fs = require('fs');

exports.onImageUpload = functions.storage.object().onFinalize(async (object) => {
  const bucket = object.bucket;
  const filePath = object.name;
  const fileName = path.basename(filePath);
  const tempFilePath = path.join(os.tmpdir(), fileName);
  const metadata = {
    contentType: object.contentType,
  };

  // Download file from bucket.
  await storage.bucket(bucket).file(filePath).download({destination: tempFilePath});

  // Resize the image and upload image back to bucket.
  await sharp(tempFilePath).resize(800, 800).toFile(tempFilePath);
  await storage.bucket(bucket).upload(tempFilePath, {destination: filePath, metadata});

  // Delete temporary file.
  fs.unlinkSync(tempFilePath);
});

4. Summary

In this tutorial, we've explored some real-world use cases of Cloud Functions. We've seen how they can be used for sending welcome emails to new users and processing images in real-time. The serverless nature of Cloud Functions makes them incredibly versatile and useful in many scenarios.

To continue your learning, consider building a project that incorporates Cloud Functions.

5. Practice Exercises

Here are a few practice exercises:

  1. Exercise 1: Create a Cloud Function that sends a goodbye email when a user deletes their account.
  2. Exercise 2: Create a Cloud Function that compresses a file when it's uploaded to a Cloud Storage bucket.
  3. Exercise 3: Build a serverless backend that uses Cloud Functions to handle HTTP requests.

Make sure to practice and experiment with Cloud Functions to gain a deeper understanding.