Gli SDK client Cloud Functions per Firebase ti consentono di chiamare le funzioni direttamente da un'app Firebase. Per chiamare una funzione dalla tua app in questo modo, scrivi e distribuisci una funzione chiamabile HTTPS in Cloud Functions, quindi aggiungi la logica client per chiamare la funzione dalla tua app.
È importante tenere presente che le funzioni richiamabili HTTPS sono simili ma non identiche alle funzioni HTTP. Per utilizzare le funzioni richiamabili HTTPS è necessario utilizzare l'SDK client per la piattaforma insieme all'API backend functions.https
(o implementare il protocollo). I callables hanno queste differenze fondamentali rispetto alle funzioni HTTP:
- Con i chiamabili, i token Firebase Authentication e FCM, se disponibili, vengono inclusi automaticamente nelle richieste.
- Il trigger
functions.https.onCall
deserializza automaticamente il corpo della richiesta e convalida i token di autenticazione.
L'SDK Firebase per Cloud Functions v0.9.1 e versioni successive interagisce con queste versioni minime dell'SDK client Firebase per supportare le funzioni chiamabili HTTPS:
- Firebase SDK per iOS 7.10.0
- Firebase SDK per Android 19.2.0
- Firebase JavaScript SDK 8.4.1
- Firebase Modular Web SDK v. 9.0
Se desideri aggiungere funzionalità simili a un'app costruita su una piattaforma non supportata, consulta le specifiche del protocollo per https.onCall
. Il resto di questa guida fornisce istruzioni su come scrivere, distribuire e chiamare una funzione richiamabile HTTPS per iOS, Android, Web, C ++ e Unity.
Scrivi e distribuisci la funzione richiamabile
Utilizzare functions.https.onCall
per creare una funzione richiamabile HTTPS. Questo metodo accetta due parametri: data
e context
facoltativo:
// Saves a message to the Firebase Realtime Database but sanitizes the text by removing swearwords.
exports.addMessage = functions.https.onCall((data, context) => {
// ...
});
Per una funzione richiamabile che salva un messaggio di testo nel database in tempo reale, ad esempio, i data
potrebbero contenere il testo del messaggio, mentre i parametri di context
rappresentano le informazioni sull'autenticazione dell'utente:
// 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;
La distanza tra la posizione della funzione richiamabile e la posizione del client chiamante può creare latenza di rete. Per ottimizzare le prestazioni, valuta la possibilità di specificare la posizione della funzione, ove applicabile, e assicurati di allineare la posizione del chiamabile con la posizione impostata quando inizializzi l'SDK sul lato client.
Restituendo il risultato
Per inviare di nuovo i dati al client, restituisci i dati che possono essere codificati in JSON. Ad esempio, per restituire il risultato di un'operazione di addizione:
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: '+',
operationResult: firstNumber + secondNumber,
};
Per restituire dati dopo un'operazione asincrona, restituisci una promessa. I dati restituiti dalla promessa vengono rispediti al cliente. Ad esempio, potresti restituire un testo disinfettato che la funzione richiamabile ha scritto al database in tempo reale:
// 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 };
})
Gestisci gli errori
Per garantire che il client ottenga dettagli utili sull'errore, restituisci gli errori da un callable lanciando (o restituendo un Promise rifiutato con) un'istanza di functions.https.HttpsError
. L'errore ha un attributo di code
che può essere uno dei valori elencati in functions.https.HttpsError
. Gli errori hanno anche un message
stringa, che per impostazione predefinita è una stringa vuota. Possono anche avere un campo details
opzionale con un valore arbitrario. Se dalle tue funzioni viene generato un errore diverso da HttpsError
, il tuo client riceve invece un errore con il messaggio INTERNAL
e il codice internal
.
Ad esempio, una funzione potrebbe generare errori di convalida dei dati e di autenticazione con messaggi di errore per tornare al client chiamante:
// 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.');
}
Distribuisci la funzione richiamabile
Dopo aver salvato una funzione richiamabile completata in index.js
, questa viene distribuita insieme a tutte le altre funzioni quando firebase deploy
. Per distribuire solo il chiamabile, utilizzare l'argomento --only
come mostrato per eseguire distribuzioni parziali :
$ firebase deploy --only functions:addMessage
Se si verificano errori di autorizzazione durante la distribuzione delle funzioni, assicurarsi che i ruoli IAM appropriati siano assegnati all'utente che esegue i comandi di distribuzione.
Configura il tuo ambiente di sviluppo client
Assicurati di soddisfare tutti i prerequisiti, quindi aggiungi le dipendenze e le librerie client richieste alla tua app.
iOS
- Segui le istruzioni per aggiungere Firebase alla tua app iOS .
- Aggiungi il pod Cloud Functions al tuo
Podfile
:pod 'Firebase/Functions'
- Salva il file, quindi esegui:
pod install
Web v9
- Segui le istruzioni per aggiungere Firebase alla tua app web .
- Aggiungi le librerie client Firebase core e Cloud Functions alla tua app:
<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>
L'SDK di Cloud Functions è disponibile anche come pacchetto npm.
- Esegui il seguente comando dal tuo terminale:
npm install firebase@8.4.1 --save
Richiede manualmente sia Firebase core che Cloud Functions:
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
- Segui le istruzioni per aggiungere Firebase alla tua app web .
- Aggiungi le librerie client Firebase core e Cloud Functions alla tua app:
<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>
L'SDK di Cloud Functions è disponibile anche come pacchetto npm.
- Esegui il seguente comando dal tuo terminale:
npm install firebase@8.4.1 --save
- Richiede manualmente sia Firebase core che Cloud Functions:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Giava
Segui le istruzioni per aggiungere Firebase alla tua app Android .
Utilizzando Firebase Android BoM , dichiara la dipendenza per la libreria Android di Cloud Functions nel file Gradle del modulo (a livello di app) (solitamente
app/build.gradle
).dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:27.0.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' }
Utilizzando Firebase Android BoM , la tua app utilizzerà sempre versioni compatibili delle librerie Firebase Android.
(Alternativa) Dichiara le dipendenze della libreria Firebase senza utilizzare BoM
Se scegli di non utilizzare Firebase BoM, devi specificare ciascuna versione della libreria Firebase nella relativa riga di dipendenza.
Tieni presente che se utilizzi più librerie Firebase nella tua app, ti consigliamo vivamente di utilizzare BoM per gestire le versioni delle librerie, il che garantisce che tutte le versioni siano compatibili.
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
Segui le istruzioni per aggiungere Firebase alla tua app Android .
Utilizzando Firebase Android BoM , dichiara la dipendenza per la libreria Android di Cloud Functions nel file Gradle del modulo (a livello di app) (solitamente
app/build.gradle
).dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:27.0.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' }
Utilizzando Firebase Android BoM , la tua app utilizzerà sempre versioni compatibili delle librerie Firebase Android.
(Alternativa) Dichiara le dipendenze della libreria Firebase senza utilizzare BoM
Se scegli di non utilizzare Firebase BoM, devi specificare ciascuna versione della libreria Firebase nella relativa riga di dipendenza.
Tieni presente che se utilizzi più librerie Firebase nella tua app, ti consigliamo vivamente di utilizzare BoM per gestire le versioni delle librerie, il che garantisce che tutte le versioni siano compatibili.
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 ++
Per C ++ con Android :
- Segui le istruzioni per aggiungere Firebase al tuo progetto C ++ .
- Aggiungi la libreria
firebase_functions
al tuo fileCMakeLists.txt
.
Per C ++ con iOS :
- Segui le istruzioni per aggiungere Firebase al tuo progetto C ++ .
- Aggiungi il pod Cloud Functions al tuo
Podfile
:pod 'Firebase/Functions'
- Salva il file, quindi esegui:
pod install
- Aggiungi i framework Firebase core e Cloud Functions dall'SDK Firebase C ++ al tuo progetto Xcode.
-
firebase.framework
-
firebase_functions.framework
-
Unità
- Segui le istruzioni per aggiungere Firebase al tuo progetto Unity .
- Aggiungi il
FirebaseFunctions.unitypackage
da Firebase Unity SDK al tuo progetto Unity.
Inizializza l'SDK del client
Inizializza un'istanza di Cloud Functions:
Swift
lazy var functions = Functions.functions()
Obiettivo-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 ###',
});
Giava
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);
Unità
functions = Firebase.Functions.DefaultInstance;
Chiama la funzione
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 text = result?.data as? String {
self.resultField.text = text
}
}
Obiettivo-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;
});
Giava
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);
}
Unità
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;
});
}
Gestisci gli errori sul client
Il client riceve un errore se il server ha generato un errore o se la promessa risultante è stata rifiutata.
Se l'errore restituito dalla funzione è di tipo function.https.HttpsError
, il client riceve il code
errore, il message
e i details
dall'errore del server. In caso contrario, l'errore contiene il messaggio INTERNAL
e il codice INTERNAL
. Consulta le indicazioni su come gestire gli errori nella funzione richiamabile.
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]
}
// ...
}
Obiettivo-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;
// ...
});
Giava
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);
// ...
Unità
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;
}
});