Improving Firebase Backend�for Flutter App through �Cloud Functions
Sasha Denisov, EPAM
Flutter and Dart GDE
About me
2
CHIEF SOFTWARE ENGINEER II
SASHA DENISOV
Sasha is an experienced software developer with a rich background, in IT for more than 20 years. He worked with different stacks in backend, frontend and mobile fields, but since 2018 his main interest is Flutter. Sasha is Chief Software Engineer and Head of Flutter Discipline in EPAM. In addition, he is a Flutter and Dart Google Developer Expert and Co-Organizer of Flutter Berlin Meetup community
Cloud Functions for Firebase
Clouds
Cloud Service Characteristics
Evolution of Cloud Services
Function
Application
Runtime
Container
OS
Virtualization
Hardware
IaaS
Function
Application
Runtime
Container
OS
Virtualization
Hardware
CaaS
Function
Application
Runtime
Container
OS
Virtualization
Hardware
PaaS
Function
Application
Runtime
Container
OS
Virtualization
Hardware
FaaS
User Management
User Management (scalable unit)
Service Provider Management
Cloud Functions
The question is
9
What exactly Firebase backend is?
Firebase
10
Traditional server backend
11
Firebase serverless backend
12
Flutter Application: Movies
13
https://github.com/denisovav/flutter_tv
Let’s add few Firebase Services
14
Firestore database for storing movies data
Storage for storing images and videos
Authentication for access control
Adding Firebase backend
https://github.com/DenisovAV/flutter_tv/tree/firebase_support
Authentication Added
16
https://pub.dev/packages/firebase_ui_auth
Cloud Function Trigger
How to to trigger a function?
Authentication Triggers
Authentication Functions Using Scenarios
Scenario
New User
How to create a Cloud Function?
npm -g install firebase-tools
�
firebase login
�
firebase init functions
4. Write your function code using JS or TS (functions/index.js)
5. Deploy functions to a production environment
firebase deploy --only functions
�
Supported Languages
AI ?
import * as functions from "firebase-functions";
�export const createUser =
exports.createUser = functions.region("europe-west1").auth.user().onCreate(async (user) => {
�if (user.photoURL) {
const avatarFileName = `avatars/${user.uid}.jpg`;
�const response = await axios.get(user.photoURL, {responseType: "arraybuffer"});
const buffer = Buffer.from(response.data, "binary");
�const file = bucket.file(avatarFileName);
await file.save(buffer, {contentType: "image/jpeg", public: true});
const uuid = randomUUID();
�updatedAvatarURL = `https://firebasestorage.googleapis.com/v0/b/${bucket.name}` +
`/o/${encodeURIComponent(file.name)}?alt=media&token=${uuid}`;
}
�// Create a new document in the `users` collection.
const doc = admin.firestore().collection("users").doc(user.uid);
�doc.set({
user.email, displayName: user.displayName, avatarURL: updatedAvatarURL, admin: false});
});
Administrator Capabilities
31
Storage Triggers
Cloud Functions Generation 2
33
Supported Languages in Gen2
Cloud Run
35
Dart on Server Side
36
Serverpod
Dart Frog
Cloud Run
37
Storage Functions Using Scenarios
Scenario
Image Uploaded
import * as functions from "firebase-functions/v2";
export const compressImage =
exports.compressMedia = functions.storage.onObjectFinalized({cpu: 2}, async (event) => {
const fileBucket = event.data.bucket; // Storage bucket containing the file.
if (!contentType.startsWith("image/")) {
return console.error("This is not an uploaded image.");
}
const bucket = admin.storage().bucket(fileBucket);
const downloadResponse = await bucket.file(filePath).download();
const imageBuffer = downloadResponse[0];
�const meta = await sharp(imageBuffer).metadata();
�const rotatedBuffer = (meta.width! < meta.height! ? await sharp(imageBuffer).rotate(90).toBuffer() : imageBuffer);
�const processedBuffer = await sharp(rotatedBuffer).resize({width: 600, height: 300, withoutEnlargement: true,
}).toBuffer();
�// Upload the processed image.
const metadata = {contentType: contentType};
const file = bucket.file(filePath);
await file.save(processedBuffer, {
metadata: metadata,
});
�return console.log("Image uploaded!");
});
The question is
42
How to notify users about new content?
Firestore Triggers
Firestore Functions Using Scenarios
Scenario
Document Added
import * as functions from "firebase-functions/v2";
�functions.setGlobalOptions({
region: "europe-west1",
});
�export const sendPushNotification = functions.firestore.onDocumentCreated("movies/{id}", async (event) => {
const movie = event.data;
� const name = movie.get("name");
const image = movie.get("image");
� const notification: admin.messaging.Message = {notification: {title: `${name} added!`,
body: "New movie was added to movies catalog, please enjoy!", imageUrl: image, },
topic: "movies",
};
� try {
const response = await admin.messaging().send(notification);
console.log("Successfully sent message:", response);
} catch (error) {
console.error("Error sending message:", error);
}
});
Firebase Cloud Messaging
48
Rest API
49
�export const getMoviesData = functions.https.onRequest(async (req, res) => {
const snapshot = await admin.firestore().collection("movies").get();
� if (snapshot.empty) {
res.status(400).send({error: "Collection of movies is empty."});
return;
}
� const data: any[] = [];
� snapshot.forEach((doc) => {
data.push({
id: doc.id,
...doc.data(),
});
});
� res.status(200).send({data: data});
});
�
52
Callable
53
await FirebaseFunctions.instance.httpsCallable('yourFunctionName').call();
More Triggers
Custom Events
55
Google Cloud Platform
56
Google Cloud Platform
57
Google Cloud Platform
58
Java Example
60
Supported Languages
61
…
Cloud Run
64
The future is bright (especially for Flutter developers)
66
THE FINAL SLIDE
THANK YOU!�QUESTIONS?