Cloud Functions for Firebase Client SDK umożliwia wywoływanie funkcji bezpośrednio z aplikacji Firebase. Aby wywołać funkcję z aplikacji w ten sposób, napisz i wdróż wywoływalną funkcję HTTPS w Cloud Functions, a następnie dodaj logikę klienta w celu wywołania funkcji z Twojej aplikacji.
Należy pamiętać, że funkcje wywoływane przez HTTPS są podobne, ale nie identyczne, jak funkcje HTTP. Aby korzystać z funkcji wywoływalnych HTTPS, musisz użyć zestawu SDK klienta dla swojej platformy wraz z functions.https
API backendu functions.https
(lub zaimplementuj protokół). Wywołania mają te kluczowe różnice w stosunku do funkcji HTTP:
- W przypadku wywołań tokeny uwierzytelniania Firebase i FCM, jeśli są dostępne, są automatycznie uwzględniane w żądaniach.
- Wyzwalacz
functions.https.onCall
automatycznie deserializuje treść żądania i weryfikuje tokeny uwierzytelniania.
Firebase SDK for Cloud Functions, wersja 0.9.1 i nowsze, współpracują z następującymi minimalnymi wersjami pakietu SDK klienta Firebase w celu obsługi funkcji HTTPS, które można wywołać:
- Firebase SDK dla iOS 7.11.0
- Firebase SDK dla Androida 19.2.0
- Pakiet Firebase JavaScript SDK 8.4.1
- Firebase Modular Web SDK, wersja 9.0
Jeśli chcesz dodać podobną funkcjonalność do aplikacji zbudowanej na nieobsługiwanej platformie, zobacz specyfikację protokołu dla https.onCall
. Pozostała część tego przewodnika zawiera instrukcje dotyczące pisania, wdrażania i wywoływania wywoływanej funkcji HTTPS dla systemów iOS, Android, sieci Web, C ++ i Unity.
Napisz i wdróż wywoływalną funkcję
Użyj functions.https.onCall
aby utworzyć wywoływalną funkcję HTTPS. Ta metoda przyjmuje dwa parametry: data
i opcjonalny context
:
// Saves a message to the Firebase Realtime Database but sanitizes the text by removing swearwords.
exports.addMessage = functions.https.onCall((data, context) => {
// ...
});
Na przykład w przypadku wywoływalnej funkcji, która zapisuje wiadomość tekstową w bazie danych czasu rzeczywistego, data
mogą zawierać tekst wiadomości, podczas gdy parametry context
reprezentują informacje o autoryzacji użytkownika:
// Message text passed from the client.
const text = data.text;
// Authentication / user information is automatically added to the request.
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;
Odległość między lokalizacją wywoływanej funkcji a lokalizacją klienta wywołującego może powodować opóźnienia w sieci. Aby zoptymalizować wydajność, rozważ określenie lokalizacji funkcji, jeśli ma to zastosowanie, i upewnij się, że lokalizacja wywoływana jest wyrównana z lokalizacją ustawioną podczas inicjowania zestawu SDK po stronie klienta.
Odesłanie wyniku
Aby wysłać dane z powrotem do klienta, zwróć dane, które mogą być zakodowane w formacie JSON. Na przykład, aby zwrócić wynik operacji dodawania:
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: '+',
operationResult: firstNumber + secondNumber,
};
Aby zwrócić dane po operacji asynchronicznej, zwróć obietnicę. Dane zwrócone przez promesę odsyłane są z powrotem do klienta. Na przykład możesz zwrócić oczyszczony tekst, który funkcja wywoływalna zapisała w bazie danych czasu rzeczywistego:
// Saving the new message to the Realtime Database.
const sanitizedMessage = sanitizer.sanitizeText(text); // Sanitize the message.
return admin.database().ref('/messages').push({
text: sanitizedMessage,
author: { uid, name, picture, email },
}).then(() => {
console.log('New Message written');
// Returning the sanitized message to the client.
return { text: sanitizedMessage };
})
Obsługuj błędy
Aby upewnić się, że klient otrzyma przydatne informacje o błędach, zwróć błędy z wywoływanego obiektu, rzucając (lub zwracając Promise odrzuconą z) wystąpieniem functions.https.HttpsError
. Błąd ma atrybut code
który może być jedną z wartości wymienionych w functions.https.HttpsError
. Błędy mają również message
postaci łańcucha, który domyślnie jest pustym ciągiem. Mogą również mieć opcjonalne pole details
z dowolną wartością. Jeśli z HttpsError
zostanie wyrzucony błąd inny niż HttpsError
, klient zamiast tego otrzyma komunikat o błędzie z komunikatem INTERNAL
i kodem internal
.
Na przykład funkcja może generować błędy walidacji danych i uwierzytelniania z komunikatami o błędach, aby powrócić do klienta wywołującego:
// Checking attribute.
if (!(typeof text === 'string') || text.length === 0) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.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 (!context.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
'while authenticated.');
}
Wdróż funkcję wywoływalną
Po zapisaniu zakończonej funkcji, którą można index.js
w index.js
, jest ona wdrażana wraz ze wszystkimi innymi funkcjami podczas uruchamiania firebase deploy
. Aby wdrożyć tylko wywoływalne, użyj argumentu --only
jak pokazano, aby wykonać częściowe wdrożenia :
$ firebase deploy --only functions:addMessage
Jeśli podczas wdrażania funkcji napotkasz błędy uprawnień, upewnij się, że odpowiednie role uprawnień są przypisane do użytkownika uruchamiającego komendy wdrażania.
Skonfiguruj środowisko programistyczne klienta
Upewnij się, że spełniasz wszystkie wymagania wstępne, a następnie dodaj wymagane zależności i biblioteki klienckie do swojej aplikacji.
iOS
- Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji na iOS .
- Dodaj
Podfile
Cloud Functions do swojegoPodfile
:pod 'Firebase/Functions'
- Zapisz plik, a następnie uruchom:
pod install
Web v9
- Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji internetowej .
- Dodaj biblioteki podstawowe Firebase i klienckie Cloud Functions do swojej aplikacji:
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase.js"></script> <script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-functions.js"></script>
Zestaw Cloud Functions SDK jest również dostępny jako pakiet npm.
- Uruchom następującą komendę na swoim terminalu:
npm install firebase@8.4.1 --save
Wymagaj ręcznie zarówno rdzenia Firebase, jak i funkcji chmury:
import { initializeApp } from 'firebase/app'; import { initializeFunctions } from 'firebase/functions';
const app = initializeApp({ projectId: '### CLOUD FUNCTIONS PROJECT ID ###', apiKey: '### FIREBASE API KEY ###', authDomain: '### FIREBASE AUTH DOMAIN ###', }); const functions = initializeFunctions(app);
Web v8
- Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji internetowej .
- Dodaj biblioteki podstawowe Firebase i klienckie Cloud Functions do swojej aplikacji:
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase.js"></script> <script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-functions.js"></script>
Zestaw Cloud Functions SDK jest również dostępny jako pakiet npm.
- Uruchom następujące polecenie z terminala:
npm install firebase@8.4.1 --save
- Wymagaj ręcznie zarówno rdzenia Firebase, jak i funkcji chmury:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Jawa
Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji na Androida .
Korzystając z narzędzia Firebase Android BoM , zadeklaruj zależność dla biblioteki Cloud Functions dla systemu Android w pliku Gradle modułu (na poziomie aplikacji) (zwykle
app/build.gradle
).dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:27.1.0') // Declare 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' }
Korzystając z BoM Firebase na Androida , Twoja aplikacja będzie zawsze używać zgodnych wersji bibliotek Firebase na Androida.
(Alternatywnie) Zadeklaruj zależności bibliotek Firebase bez korzystania z BoM
Jeśli zdecydujesz się nie używać BoM Firebase, musisz określić każdą wersję biblioteki Firebase w jej wierszu zależności.
Pamiętaj, że jeśli używasz wielu bibliotek Firebase w swojej aplikacji, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewnia zgodność wszystkich wersji.
dependencies { // Declare 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:19.2.0' }
Kotlin + KTX
Postępuj zgodnie z instrukcjami, aby dodać Firebase do swojej aplikacji na Androida .
Korzystając z narzędzia Firebase Android BoM , zadeklaruj zależność dla biblioteki Cloud Functions dla systemu Android w pliku Gradle modułu (na poziomie aplikacji) (zwykle
app/build.gradle
).dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:27.1.0') // Declare 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-ktx' }
Korzystając z BoM Firebase na Androida , Twoja aplikacja będzie zawsze używać zgodnych wersji bibliotek Firebase na Androida.
(Alternatywnie) Zadeklaruj zależności bibliotek Firebase bez korzystania z BoM
Jeśli zdecydujesz się nie używać BoM Firebase, musisz określić każdą wersję biblioteki Firebase w jej wierszu zależności.
Pamiętaj, że jeśli używasz wielu bibliotek Firebase w swojej aplikacji, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewnia zgodność wszystkich wersji.
dependencies { // Declare 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-ktx:19.2.0' }
C ++
Dla C ++ z systemem Android :
- Postępuj zgodnie z instrukcjami, aby dodać Firebase do projektu C ++ .
- Dodaj bibliotekę
firebase_functions
do plikuCMakeLists.txt
.
Dla C ++ z iOS :
- Postępuj zgodnie z instrukcjami, aby dodać Firebase do projektu C ++ .
- Dodaj
Podfile
Cloud Functions do swojegoPodfile
:pod 'Firebase/Functions'
- Zapisz plik, a następnie uruchom:
pod install
- Dodaj rdzeń Firebase i struktury Cloud Functions z pakietu Firebase C ++ SDK do projektu Xcode.
-
firebase.framework
-
firebase_functions.framework
-
Jedność
- Postępuj zgodnie z instrukcjami, aby dodać Firebase do projektu Unity .
- Dodaj pakiet
FirebaseFunctions.unitypackage
z pakietu Firebase Unity SDK do projektu Unity.
Zainicjuj pakiet SDK klienta
Zainicjuj wystąpienie Cloud Functions:
Szybki
lazy var functions = Functions.functions()
Cel C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
Web v8
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 v9
initializeApp({
projectId: '### CLOUD FUNCTIONS PROJECT ID ###',
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
});
Jawa
private FirebaseFunctions mFunctions; // ... mFunctions = FirebaseFunctions.getInstance();
Kotlin + KTX
private lateinit var functions: FirebaseFunctions // ... functions = Firebase.functions
C ++
firebase::functions::Functions* functions;
// ...
functions = firebase::functions::Functions::GetInstance(app);
Jedność
functions = Firebase.Functions.DefaultInstance;
Wywołaj funkcję
Szybki
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 text = result?.data as? String {
self.resultField.text = text
}
}
Cel C
[[_functions HTTPSCallableWithName:@"addMessage"] callWithObject:@{@"text": _inputField.text}
completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
if (error) {
if (error.domain == FIRFunctionsErrorDomain) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[FIRFunctionsErrorDetailsKey];
}
// ...
}
self->_resultField.text = result.data;
}];
Web v8
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
Web v9
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;
});
Jawa
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; } }); }
Kotlin + KTX
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 } }
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);
}
Jedność
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;
});
}
Obsługuj błędy po stronie klienta
Klient otrzymuje błąd, jeśli serwer wyrzucił błąd lub jeśli wynikająca z niego obietnica została odrzucona.
Jeśli błąd zwrócony przez funkcję jest typu function.https.HttpsError
, klient otrzymuje code
błędu, message
i details
z błędu serwera. W przeciwnym razie błąd zawiera komunikat INTERNAL
i kod INTERNAL
. Zobacz wskazówki dotyczące obsługi błędów w wywoływanej funkcji.
Szybki
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]
}
// ...
}
Cel C
if (error) {
if (error.domain == FIRFunctionsErrorDomain) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[FIRFunctionsErrorDetailsKey];
}
// ...
}
Web v8
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 v9
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;
// ...
});
Jawa
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(); } // ... } // ... } });
Kotlin + KTX
addMessage(inputMessage) .addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { val code = e.code val details = e.details } // ... } // ... })
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);
// ...
Jedność
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;
}
});