Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Supercharge your app with Cloud Functions for F...

Supercharge your app with Cloud Functions for Firebase

Building amazing mobile apps has become a lot easier thanks to modern UI frameworks like SwiftUI and Jetpack Compose.

But sometimes, you need to run some code on the server

* to orchestrate API calls
* to write business logic once, and use from all your mobile clients
* for long running process that you don’t want to run on the client

However, setting up your own server sounds like a lot of work, and like a maintenance nightmare.

Cloud Functions for Firebase to the rescue! They allow you to build a serverless backend that automatically scales to your application’s needs. You can call them from your mobile app, in response to events in other Firebase services, such as when a new user is created (or deleted), or a document was written to Firestore, and much more!

In this talk, you will learn what Cloud Functions are, what the benefits of using them are, the step-by-step of calling these functions from other Firebase products and how to use them in your Android and iOS apps.

Peter Friese

January 26, 2023
Tweet

More Decks by Peter Friese

Other Decks in Programming

Transcript

  1. Supercharge your app Supercharge your app with Cloud Functions with

    Cloud Functions Photo by Johannes Plenio on Unsplash
  2. Codename Sofia ✨ Add links via iOS Share Extension ✨

    Readability ✨ Extract OpenGraph Metadata ✨ Summarise (via GPT-3)
  3. Di ff erent ways to call your functions Listen for

    HTTP requests Call a function from your app with extra context HTTPS Callable
  4. Di ff erent ways to call your functions Using crontab

    or AppEngine cron.yaml syntax For resource-intensive, long- running tasks Scheduled In a queue
  5. Di ff erent ways to call your functions Data wri

    tt en New user created User signing in Image uploaded Crashlytics ale r Analytics Conversions File deleted Data deleted Test run completed Data updated New con fi guration Con fi guration rollback React to events
  6. Cloud Firestore Triggers onCreate(change, context) onUpdate(change, context) onDelete(change, context) onWrite(change,

    context) Execute a Cloud Function for the following events: const uid = context.auth.uid; const name = context.auth.token.name || null; const picture = context.auth.token.picture || null; const email = context.auth.token.email || null;
  7. Store readable HTML for link Firebase Backend Cloud Firestore doc(

    ... ).onCreate() Server Web Site Client Cloud Functions
  8. export const storeReadableLink = functions.firestore .document("artifacts/{documentId}") .onCreate(async (documentSnapshot) => {

    const url = documentSnapshot.data().url; const metadata = await parser.parse(url); const artifactDocument = documentSnapshot.data() as ArtifactDocument; if (!artifactDocument.readableHTML && metadata.content) { artifactDocument.readableHTML = metadata.content; } // update the document in Firestore return documentSnapshot.ref.update(artifactDocument); }); Store readable HTML for link
  9. Callable Functions onCall(data, context) Call a Cloud Function directly from

    your app const uid = context.auth.uid; const name = context.auth.token.name || null; const picture = context.auth.token.picture || null; const email = context.auth.token.email || null; onRequest(request, response)
  10. export const summarise = functions.https .onCall(async (data) => { const

    url = data; const completion = await openai.createCompletion({ model: "text-davinci-001", prompt: `Summarize this article: ${url}`, }); const summary = completion.data.choices[0].text; return summary; }); Summarise a rt icle
  11. name: auth-chat version: 0.2.0 specVersion: v1beta displayName: Authenticate with Stream

    Chat description: Synchronizes Firebase Authentication users with Stream, and creates and revoke Stream Chat authentication tokens. license: Apache-2.0 author: authorName: Stream url: https: / / getstream.io/ sourceUrl: https: // github.com/GetStream/stream-firebase-extensions/tree/ main/auth-chat billingRequired: true params: - param: LOCATION label: Cloud Functions location description: >- Where do you want to deploy the functions created for this extension? type: select extension.yaml
  12. import * as admin from "firebase-admin"; import * as functions

    from "firebase-functions"; import { StreamChat } from "stream-chat"; admin.initializeApp(); const serverClient = StreamChat.getInstance( process.env.STREAM_API_KEY!, process.env.STREAM_API_SECRET!, ); // When a user is created in Firebase an associated Stream account is also created. export const createStreamUser = functions.auth.user().onCreate(async (user) => { functions.logger.log("Firebase user created", user); / / Create user using the serverClient. const response = await serverClient.upsertUser({ id: user.uid, name: user.displayName, email: user.email, image: user.photoURL, }); index.ts
  13. import * as functions from "firebase-functions"; import { StreamChat }

    from "stream-chat"; admin.initializeApp(); const serverClient = StreamChat.getInstance( process.env.STREAM_API_KEY!, process.env.STREAM_API_SECRET!, ); // When a user is created in Firebase an associated Stream account is also created. export const createStreamUser = functions.auth.user().onCreate(async (user) => { functions.logger.log("Firebase user created", user); / / Create user using the serverClient. const response = await serverClient.upsertUser({ id: user.uid, name: user.displayName, email: user.email, image: user.photoURL, }); functions.logger.log("Stream user created", response); return response; }); index.ts
  14. What’s new in Cloud Functions? Fewer cold sta rt s

    Concurrency Codebases Skip no-op deploys 2nd gen runtime Faster deployments Parameterized con fi gs Type-safe con fi gurations Suppo rt for Cloud Secret Manager Try them now Use alongside v1 functions Emulator suppo r