ערכות ה-SDK של הלקוח Cloud Functions for Firebase מאפשרות לקרוא לפונקציות ישירות מאפליקציית Firebase. כדי לקרוא לפונקציה מהאפליקציה בדרך הזו, צריך לכתוב ולפרוס פונקציה שאפשר לקרוא לה באמצעות HTTP ב-Cloud Functions, ואז להוסיף לוגיקה של לקוח כדי לקרוא לפונקציה מהאפליקציה.
חשוב לזכור שפונקציות שאפשר להפעיל באמצעות HTTP דומות לפונקציות HTTP, אבל לא זהות להן. כדי להשתמש בפונקציות שאפשר להפעיל באמצעות HTTP, צריך להשתמש ב-Client SDK של הפלטפורמה שלכם יחד עם ה-API של ה-Backend (או להטמיע את הפרוטוקול). ההבדלים העיקריים בין פונקציות שאפשר להפעיל לבין פונקציות HTTP:
- כשמשתמשים בפונקציות שאפשר להפעיל, אסימוני Firebase Authentication, אסימוני FCM ואסימוני App Check, אם הם זמינים, נכללים אוטומטית בבקשות.
- הטריגר מבצע באופן אוטומטי דה-סריאליזציה של גוף הבקשה ומאמת את טוקני ההרשאה.
Firebase SDK ל-Cloud Functions דור שני ומעלה פועל בשילוב עם הגרסאות המינימליות הבאות של Firebase client SDK כדי לתמוך בפונקציות שאפשר להפעיל באמצעות HTTPS:
- Firebase SDK ל-Apple פלטפורמות 11.15.0
- Firebase SDK for Android 21.2.1
- Firebase Modular Web SDK v. 9.7.0
אם רוצים להוסיף פונקציונליות דומה לאפליקציה שנוצרה בפלטפורמה שלא נתמכת, אפשר לעיין במפרט הפרוטוקול של https.onCall
. בהמשך המדריך מוסבר איך לכתוב, לפרוס ולהפעיל פונקציה שניתן להפעיל באמצעות HTTP בפלטפורמות של אפל, ב-Android, באינטרנט, ב-C++ וב-Unity.
כתיבה ופריסה של פונקציה שאפשר להפעיל
משתמשים ב-functions.https.onCall
כדי ליצור פונקציה שאפשר להפעיל באמצעות HTTPS. השיטה הזו מקבלת שני פרמטרים: data
ו-context
(אופציונלי):
// Saves a message to the Firebase Realtime Database but sanitizes the // text by removing swearwords. exports.addMessage = functions.https.onCall((data, context) => { // ... });
לדוגמה, בפונקציה שאפשר להפעיל כדי לשמור הודעת טקסט ב-Realtime Database, הפרמטר data
יכול להכיל את הטקסט של ההודעה, והפרמטרים context
יכולים לייצג את פרטי אימות המשתמש:
// Message text passed from the client.
const text = request.data.text;
// Authentication / user information is automatically added to the request.
const uid = request.auth.uid;
const name = request.auth.token.name || null;
const picture = request.auth.token.picture || null;
const email = request.auth.token.email || null;
המרחק בין המיקום של הפונקציה שאפשר להפעיל לבין המיקום של הלקוח שמפעיל אותה יכול ליצור זמן אחזור ברשת. כדי לשפר את הביצועים, כדאי לציין את מיקום הפונקציה במקרים הרלוונטיים, ולוודא שהמיקום של הפונקציה שניתן להפעלה תואם למיקום שהוגדר כשמפעילים את ה-SDK בצד הלקוח.
אפשר גם לצרף App Checkאישור כדי להגן על משאבי ה-Backend מפני ניצול לרעה, כמו הונאת חיוב או פישינג. במאמר הפעלת האכיפה של App Check ב-Cloud Functions מוסבר איך עושים את זה.
החזרת התוצאה
כדי לשלוח נתונים חזרה ללקוח, צריך להחזיר נתונים שאפשר לקודד ב-JSON. לדוגמה, כדי להחזיר את התוצאה של פעולת חיבור:
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: "+",
operationResult: firstNumber + secondNumber,
};
כדי להחזיר נתונים אחרי פעולה אסינכרונית, מחזירים הבטחה. הנתונים שמוחזרים על ידי ההבטחה נשלחים בחזרה ללקוח. לדוגמה, אפשר להחזיר טקסט שעבר סניטציה, שהפונקציה שאפשר לקרוא לה כתבה אל Realtime Database:
// Saving the new message to the Realtime Database.
const sanitizedMessage = sanitizer.sanitizeText(text); // Sanitize message.
return getDatabase().ref("/messages").push({
text: sanitizedMessage,
author: {uid, name, picture, email},
}).then(() => {
logger.info("New Message written");
// Returning the sanitized message to the client.
return {text: sanitizedMessage};
})
טיפול בשגיאות
כדי לוודא שהלקוח יקבל פרטי שגיאה שימושיים, צריך להחזיר שגיאות מ-callable על ידי הפעלה (או החזרה של Promise שנדחה עם) מופע של functions.https.HttpsError
.
לשגיאה יש מאפיין code
שיכול להיות אחד מהערכים שמפורטים בכתובת functions.https.HttpsError
.
השגיאות כוללות גם מחרוזת message
, שערך ברירת המחדל שלה הוא מחרוזת ריקה. יכול להיות שיהיה להם גם שדה details
אופציונלי עם ערך שרירותי. אם הפונקציות שלכם מחזירות שגיאה אחרת מלבד HttpsError
, הלקוח מקבל שגיאה עם ההודעה INTERNAL
והקוד internal
.
לדוגמה, פונקציה יכולה להחזיר שגיאות של אימות נתונים ואימות עם הודעות שגיאה ללקוח שקורא לפונקציה:
// Checking attribute.
if (!(typeof text === "string") || text.length === 0) {
// Throwing an HttpsError so that the client gets the error details.
throw new HttpsError("invalid-argument", "The function must be called " +
"with one arguments \"text\" containing the message text to add.");
}
// Checking that the user is authenticated.
if (!request.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new HttpsError("failed-precondition", "The function must be " +
"called while authenticated.");
}
פריסת הפונקציה שאפשר לקרוא לה
אחרי ששומרים פונקציה שאפשר להפעיל ב-index.js
, היא נפרסת יחד עם כל הפונקציות האחרות כשמריצים את firebase deploy
.
כדי לפרוס רק את הפונקציה שאפשר להפעיל, משתמשים בארגומנט --only
כמו בדוגמה כדי לבצע פריסות חלקיות:
firebase deploy --only functions:addMessage
אם נתקלתם בשגיאות הרשאות כשפרסתם פונקציות, ודאו שתפקידי ה-IAM המתאימים הוקצו למשתמש שמריץ את פקודות הפריסה.
הגדרת סביבת הפיתוח של הלקוח
מוודאים שאתם עומדים בדרישות המוקדמות, ואז מוסיפים לאפליקציה את התלות הנדרשת ואת ספריות הלקוח.
iOS+
פועלים לפי ההוראות להוספת Firebase לאפליקציית Apple.
משתמשים ב-Swift Package Manager כדי להתקין ולנהל יחסי תלות ב-Firebase.
- ב-Xcode, כשהפרויקט של האפליקציה פתוח, עוברים אל File > Add Packages (קובץ > הוספת חבילות).
- כשמוצגת בקשה, מוסיפים את מאגר Firebase Apple platforms SDK:
- בוחרים את הספרייה Cloud Functions.
- מוסיפים את הדגל
-ObjC
לקטע Other Linker Flags בהגדרות הבנייה של היעד. - אחרי שתסיימו, פלטפורמת Xcode תתחיל באופן אוטומטי לטפל ביחסי התלות ולהוריד אותם ברקע.
https://github.com/firebase/firebase-ios-sdk.git
Web
- פועלים לפי ההוראות כדי להוסיף את Firebase לאפליקציית האינטרנט. חשוב להריץ את הפקודה הבאה מהטרמינל:
npm install firebase@11.10.0 --save
צריך לדרוש באופן ידני גם את Firebase Core וגם את Cloud Functions:
import { initializeApp } from 'firebase/app'; import { getFunctions } from 'firebase/functions'; const app = initializeApp({ projectId: '### CLOUD FUNCTIONS PROJECT ID ###', apiKey: '### FIREBASE API KEY ###', authDomain: '### FIREBASE AUTH DOMAIN ###', }); const functions = getFunctions(app);
Web
- פועלים לפי ההוראות להוספת Firebase לאפליקציית האינטרנט.
- מוסיפים לאפליקציה את ליבת Firebase ואת ספריות הלקוח Cloud Functions:
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-functions.js"></script>
Cloud Functions SDK זמין גם כחבילת npm.
- מריצים את הפקודה הבאה מהטרמינל:
npm install firebase@8.10.1 --save
- צריך לדרוש באופן ידני גם את Firebase Core וגם את Cloud Functions:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Kotlin
פועלים לפי ההוראות להוספת Firebase לאפליקציית Android.
בקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל
<project>/<app-module>/build.gradle.kts
או<project>/<app-module>/build.gradle
), מוסיפים את התלות בספריית Cloud Functions ל-Android. מומלץ להשתמש ב-Firebase Android BoM כדי לשלוט בניהול הגרסאות של הספריות.dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.16.0")) // Add the dependency for the Cloud Functions library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-functions") }
באמצעות Firebase Android BoM, האפליקציה תמיד תשתמש בגרסאות תואמות של ספריות Firebase ל-Android.
(חלופה) מוסיפים תלות בספריית Firebase בלי להשתמש ב-BoM
אם לא משתמשים ב-Firebase BoM, צריך לציין את הגרסה של כל ספריית Firebase בשורת התלות שלה.
הערה: אם אתם משתמשים בכמה ספריות Firebase באפליקציה, מומלץ מאוד להשתמש ב-BoM כדי לנהל את גרסאות הספריות, וכך לוודא שכל הגרסאות תואמות.
dependencies { // Add the dependency for the Cloud Functions library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-functions:21.2.1") }
Java
פועלים לפי ההוראות להוספת Firebase לאפליקציית Android.
בקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל
<project>/<app-module>/build.gradle.kts
או<project>/<app-module>/build.gradle
), מוסיפים את התלות בספריית Cloud Functions ל-Android. מומלץ להשתמש ב-Firebase Android BoM כדי לשלוט בניהול הגרסאות של הספריות.dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.16.0")) // Add the dependency for the Cloud Functions library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-functions") }
באמצעות Firebase Android BoM, האפליקציה תמיד תשתמש בגרסאות תואמות של ספריות Firebase ל-Android.
(חלופה) מוסיפים תלות בספריית Firebase בלי להשתמש ב-BoM
אם לא משתמשים ב-Firebase BoM, צריך לציין את הגרסה של כל ספריית Firebase בשורת התלות שלה.
הערה: אם אתם משתמשים בכמה ספריות Firebase באפליקציה, מומלץ מאוד להשתמש ב-BoM כדי לנהל את גרסאות הספריות, וכך לוודא שכל הגרסאות תואמות.
dependencies { // Add the dependency for the Cloud Functions library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-functions:21.2.1") }
Dart
פועלים לפי ההוראות להוספת Firebase לאפליקציית Flutter.
מהרמה הבסיסית (root) של פרויקט Flutter, מריצים את הפקודה הבאה כדי להתקין את הפלאגין:
flutter pub add cloud_functions
בסיום התהליך, בונים מחדש את אפליקציית Flutter:
flutter run
אחרי ההתקנה, אפשר לגשת לפלאגין
cloud_functions
על ידי ייבוא שלו לקוד Dart:import 'package:cloud_functions/cloud_functions.dart';
C++
C++ עם Android:
- פועלים לפי ההוראות להוספת Firebase לפרויקט C++.
- מוסיפים את הספרייה
firebase_functions
לקובץCMakeLists.txt
.
C++ עם פלטפורמות של אפל:
- פועלים לפי ההוראות להוספת Firebase לפרויקט C++.
- מוסיפים את ה-Pod Cloud Functions אל
Podfile
:pod 'Firebase/Functions'
- שומרים את הקובץ ומריצים:
pod install
- מוסיפים את Firebase core ואת מסגרות Cloud Functions מ-Firebase SDK לפרויקט Xcode.C++
firebase.framework
firebase_functions.framework
Unity
- פועלים לפי ההוראות להוספת Firebase לפרויקט Unity.
- מוסיפים את
FirebaseFunctions.unitypackage
מ-Firebase Unity SDK לפרויקט Unity.
אתחול ה-SDK של הלקוח
מאתחלים מופע של Cloud Functions:
Swift
lazy var functions = Functions.functions()
Objective-C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
Web
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FUNCTIONS PROJECT ID ###'
databaseURL: 'https://### YOUR DATABASE NAME ###.firebaseio.com',
});
// Initialize Cloud Functions through Firebase
var functions = firebase.functions();
Web
const app = initializeApp({
projectId: '### CLOUD FUNCTIONS PROJECT ID ###',
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
});
const functions = getFunctions(app);
Kotlin
private lateinit var functions: FirebaseFunctions // ... functions = Firebase.functions
Java
private FirebaseFunctions mFunctions; // ... mFunctions = FirebaseFunctions.getInstance();
Dart
final functions = FirebaseFunctions.instance;
C++
firebase::functions::Functions* functions;
// ...
functions = firebase::functions::Functions::GetInstance(app);
Unity
functions = Firebase.Functions.DefaultInstance;
הפעלת הפונקציה
Swift
functions.httpsCallable("addMessage").call(["text": inputField.text]) { result, error in
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
}
// ...
}
if let data = result?.data as? [String: Any], let text = data["text"] as? String {
self.resultField.text = text
}
}
Objective-C
[[_functions HTTPSCallableWithName:@"addMessage"] callWithObject:@{@"text": _inputField.text}
completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
if (error) {
if ([error.domain isEqual:@"com.firebase.functions"]) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[@"details"];
}
// ...
}
self->_resultField.text = result.data[@"text"];
}];
Web
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
Web
import { getFunctions, httpsCallable } from "firebase/functions";
const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
/** @type {any} */
const data = result.data;
const sanitizedMessage = data.text;
});
Kotlin
private fun addMessage(text: String): Task<String> { // Create the arguments to the callable function. val data = hashMapOf( "text" to text, "push" to true, ) return functions .getHttpsCallable("addMessage") .call(data) .continueWith { task -> // This continuation runs on either success or failure, but if the task // has failed then result will throw an Exception which will be // propagated down. val result = task.result?.data as String result } }
Java
private Task<String> addMessage(String text) { // Create the arguments to the callable function. Map<String, Object> data = new HashMap<>(); data.put("text", text); data.put("push", true); return mFunctions .getHttpsCallable("addMessage") .call(data) .continueWith(new Continuation<HttpsCallableResult, String>() { @Override public String then(@NonNull Task<HttpsCallableResult> task) throws Exception { // This continuation runs on either success or failure, but if the task // has failed then getResult() will throw an Exception which will be // propagated down. String result = (String) task.getResult().getData(); return result; } }); }
Dart
final result = await FirebaseFunctions.instance.httpsCallable('addMessage').call(
{
"text": text,
"push": true,
},
);
_response = result.data as String;
C++
firebase::Future<firebase::functions::HttpsCallableResult> AddMessage(
const std::string& text) {
// Create the arguments to the callable function.
firebase::Variant data = firebase::Variant::EmptyMap();
data.map()["text"] = firebase::Variant(text);
data.map()["push"] = true;
// Call the function and add a callback for the result.
firebase::functions::HttpsCallableReference doSomething =
functions->GetHttpsCallable("addMessage");
return doSomething.Call(data);
}
Unity
private Task<string> addMessage(string text) {
// Create the arguments to the callable function.
var data = new Dictionary<string, object>();
data["text"] = text;
data["push"] = true;
// Call the function and extract the operation from the result.
var function = functions.GetHttpsCallable("addMessage");
return function.CallAsync(data).ContinueWith((task) => {
return (string) task.Result.Data;
});
}
טיפול בשגיאות בצד הלקוח
הלקוח מקבל שגיאה אם השרת זרק שגיאה או אם ההבטחה שנוצרה נדחתה.
אם השגיאה שמוחזרת על ידי הפונקציה היא מסוג function.https.HttpsError
, הלקוח מקבל את השגיאה code
, message
ו-details
משגיאת השרת. אחרת, השגיאה מכילה את ההודעה INTERNAL
ואת הקוד INTERNAL
. במאמר הזה מוסבר איך לטפל בשגיאות בפונקציה שאפשר להפעיל.
Swift
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
}
// ...
}
Objective-C
if (error) {
if ([error.domain isEqual:@"com.firebase.functions"]) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[@"details"];
}
// ...
}
Web
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
})
.catch((error) => {
// Getting the Error details.
var code = error.code;
var message = error.message;
var details = error.details;
// ...
});
Web
import { getFunctions, httpsCallable } from "firebase/functions";
const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
/** @type {any} */
const data = result.data;
const sanitizedMessage = data.text;
})
.catch((error) => {
// Getting the Error details.
const code = error.code;
const message = error.message;
const details = error.details;
// ...
});
Kotlin
addMessage(inputMessage) .addOnCompleteListener { task -> if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { val code = e.code val details = e.details } } }
Java
addMessage(inputMessage) .addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { if (!task.isSuccessful()) { Exception e = task.getException(); if (e instanceof FirebaseFunctionsException) { FirebaseFunctionsException ffe = (FirebaseFunctionsException) e; FirebaseFunctionsException.Code code = ffe.getCode(); Object details = ffe.getDetails(); } } } });
Dart
try {
final result =
await FirebaseFunctions.instance.httpsCallable('addMessage').call();
} on FirebaseFunctionsException catch (error) {
print(error.code);
print(error.details);
print(error.message);
}
C++
void OnAddMessageCallback(
const firebase::Future<firebase::functions::HttpsCallableResult>& future) {
if (future.error() != firebase::functions::kErrorNone) {
// Function error code, will be kErrorInternal if the failure was not
// handled properly in the function call.
auto code = static_cast<firebase::functions::Error>(future.error());
// Display the error in the UI.
DisplayError(code, future.error_message());
return;
}
const firebase::functions::HttpsCallableResult* result = future.result();
firebase::Variant data = result->data();
// This will assert if the result returned from the function wasn't a string.
std::string message = data.string_value();
// Display the result in the UI.
DisplayResult(message);
}
// ...
// ...
auto future = AddMessage(message);
future.OnCompletion(OnAddMessageCallback);
// ...
Unity
addMessage(text).ContinueWith((task) => {
if (task.IsFaulted) {
foreach (var inner in task.Exception.InnerExceptions) {
if (inner is FunctionsException) {
var e = (FunctionsException) inner;
// Function error code, will be INTERNAL if the failure
// was not handled properly in the function call.
var code = e.ErrorCode;
var message = e.ErrorMessage;
}
}
} else {
string result = task.Result;
}
});
מומלץ: מניעת ניצול לרעה באמצעות App Check
לפני שמשיקים את האפליקציה, כדאי להפעיל את App Check כדי לוודא שרק האפליקציות שלכם יוכלו לגשת לנקודות הקצה של הפונקציות שאפשר להפעיל.