Chiama le funzioni dalla tua app


Gli SDK client Cloud Functions for Firebase ti consentono di chiamare funzioni direttamente da un'app Firebase. Per chiamare una funzione dalla tua app in questo modo, scrivi e distribuisci una funzione HTTP Callable in Cloud Functions, quindi aggiungi la logica client per chiamare la funzione dalla tua app.

È importante tenere presente che le funzioni richiamabili HTTP sono simili ma non identiche alle funzioni HTTP. Per utilizzare le funzioni richiamabili HTTP devi utilizzare l'SDK client per la tua piattaforma insieme all'API backend (o implementare il protocollo). I chiamabili presentano queste differenze fondamentali rispetto alle funzioni HTTP:

  • Con i callable, i token di autenticazione Firebase, i token FCM e i token App Check, quando disponibili, vengono automaticamente inclusi nelle richieste.
  • Il trigger deserializza automaticamente il corpo della richiesta e convalida i token di autenticazione.

L'SDK Firebase per Cloud Functions di seconda generazione e versioni successive interagisce con queste versioni minime dell'SDK client Firebase per supportare le funzioni richiamabili HTTPS:

  • SDK Firebase per piattaforme Apple 10.19.0
  • SDK Firebase per Android 20.4.0
  • SDK Web modulare Firebase versione 9.7.0

Se desideri aggiungere funzionalità simili a un'app creata su una piattaforma non supportata, consulta la Specifica del protocollo per https.onCall . Il resto di questa guida fornisce istruzioni su come scrivere, distribuire e chiamare una funzione richiamabile HTTP per piattaforme Apple, Android, Web, C++ e Unity.

Scrivere e distribuire la funzione richiamabile

Utilizza functions.https.onCall per creare una funzione richiamabile HTTPS. Questo metodo accetta due parametri: data e context opzionale:

// 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 Realtime Database, ad esempio, data potrebbero contenere il testo del messaggio, mentre i parametri 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.

Facoltativamente, puoi allegare un attestato di App Check per proteggere le tue risorse di backend da abusi, come frodi nella fatturazione o phishing. Consulta Abilitare l'applicazione di App Check per Cloud Functions .

Restituendo il risultato

Per inviare nuovamente i dati al client, restituire 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 i dati dopo un'operazione asincrona, restituire una promessa. I dati restituiti dalla promessa vengono rispediti al client. Ad esempio, potresti restituire il testo ripulito che la funzione richiamabile ha scritto nel Realtime Database:

// 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 };
})

Gestire gli errori

Per garantire che il client ottenga dettagli utili sull'errore, restituire gli errori da un callable lanciando (o restituendo una Promise rifiutata con) un'istanza functions.https.HttpsError . L'errore ha un attributo code che può essere uno dei valori elencati in functions.https.HttpsError . Gli errori hanno anche una stringa message , 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 da restituire 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.');
}

Distribuire la funzione richiamabile

Dopo aver salvato una funzione richiamabile completata all'interno di index.js , questa viene distribuita insieme a tutte le altre funzioni quando esegui firebase deploy . Per distribuire solo il richiamabile, utilizzare l'argomento --only come mostrato per eseguire distribuzioni parziali :

firebase deploy --only functions:addMessage

Se riscontri errori di autorizzazione durante la distribuzione delle funzioni, assicurati che i ruoli IAM appropriati siano assegnati all'utente che esegue i comandi di distribuzione.

Configura l'ambiente di sviluppo del tuo 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 Apple .

Utilizza Swift Package Manager per installare e gestire le dipendenze di Firebase.

  1. In Xcode, con il progetto dell'app aperto, vai a File > Add Packages .
  2. Quando richiesto, aggiungi il repository SDK delle piattaforme Apple Firebase:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Scegli la libreria Cloud Functions.
  5. Aggiungi il flag -ObjC alla sezione Altri flag del linker delle impostazioni di build del tuo target.
  6. Al termine, Xcode inizierà automaticamente a risolvere e scaricare le tue dipendenze in background.

API modulare Web

  1. Segui le istruzioni per aggiungere Firebase alla tua app Web . Assicurati di eseguire il seguente comando dal tuo terminale:
    npm install firebase@10.7.1 --save
    
  2. Richiedi manualmente sia Firebase Core che 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);
    

API con spazio dei nomi Web

  1. Segui le istruzioni per aggiungere Firebase alla tua app Web .
  2. Aggiungi le librerie client Firebase Core e Cloud Functions alla tua app:
    <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>
    

L'SDK Cloud Functions è disponibile anche come pacchetto npm.

  1. Esegui il seguente comando dal tuo terminale:
    npm install firebase@8.10.1 --save
    
  2. Richiedi manualmente sia Firebase Core che Cloud Functions:
    const firebase = require("firebase");
    // Required for side-effects
    require("firebase/functions");
    

Kotlin+KTX

  1. Segui le istruzioni per aggiungere Firebase alla tua app Android .

  2. Nel file Gradle del modulo (a livello di app) (solitamente <project>/<app-module>/build.gradle.kts o <project>/<app-module>/build.gradle ), aggiungi la dipendenza per Cloud Functions libreria per Android. Ti consigliamo di utilizzare la distinta base Android Firebase per controllare il controllo delle versioni della libreria.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.7.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")
    }
    

    Utilizzando la distinta base Firebase per Android , la tua app utilizzerà sempre le versioni compatibili delle librerie Firebase Android.

    (Alternativa) Aggiungi le dipendenze della libreria Firebase senza utilizzare la distinta base

    Se scegli di non utilizzare la distinta base Firebase, 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 la distinta base per gestire le versioni della libreria, il che garantisce che tutte le versioni siano compatibili.

    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:20.4.0")
    }
    
    Cerchi un modulo di libreria specifico per Kotlin? A partire da ottobre 2023 (Firebase BoM 32.5.0) , sia gli sviluppatori Kotlin che Java potranno dipendere dal modulo della libreria principale (per i dettagli, vedere le FAQ su questa iniziativa ).

Java

  1. Segui le istruzioni per aggiungere Firebase alla tua app Android .

  2. Nel file Gradle del modulo (a livello di app) (solitamente <project>/<app-module>/build.gradle.kts o <project>/<app-module>/build.gradle ), aggiungi la dipendenza per Cloud Functions libreria per Android. Ti consigliamo di utilizzare la distinta base Android Firebase per controllare il controllo delle versioni della libreria.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.7.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")
    }
    

    Utilizzando la distinta base Firebase per Android , la tua app utilizzerà sempre le versioni compatibili delle librerie Firebase Android.

    (Alternativa) Aggiungi le dipendenze della libreria Firebase senza utilizzare la distinta base

    Se scegli di non utilizzare la distinta base Firebase, 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 la distinta base per gestire le versioni della libreria, il che garantisce che tutte le versioni siano compatibili.

    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:20.4.0")
    }
    
    Cerchi un modulo di libreria specifico per Kotlin? A partire da ottobre 2023 (Firebase BoM 32.5.0) , sia gli sviluppatori Kotlin che Java potranno dipendere dal modulo della libreria principale (per i dettagli, vedere le FAQ su questa iniziativa ).

Dart

  1. Segui le istruzioni per aggiungere Firebase alla tua app Flutter .

  2. Dalla radice del tuo progetto Flutter, esegui il comando seguente per installare il plugin:

    flutter pub add cloud_functions
    
  3. Una volta completato, ricostruisci la tua applicazione Flutter:

    flutter run
    
  4. Una volta installato, puoi accedere al plugin cloud_functions importandolo nel tuo codice Dart:

    import 'package:cloud_functions/cloud_functions.dart';
    

C++

Per C++ con Android :

  1. Segui le istruzioni per aggiungere Firebase al tuo progetto C++ .
  2. Aggiungi la libreria firebase_functions al tuo file CMakeLists.txt .

Per C++ con piattaforme Apple :

  1. Segui le istruzioni per aggiungere Firebase al tuo progetto C++ .
  2. Aggiungi il pod Cloud Functions al tuo Podfile :
    pod 'Firebase/Functions'
  3. Salvare il file, quindi eseguire:
    pod install
  4. Aggiungi il core Firebase e i framework Cloud Functions dall'SDK Firebase C++ al tuo progetto Xcode.
    • firebase.framework
    • firebase_functions.framework

Unità

  1. Segui le istruzioni per aggiungere Firebase al tuo progetto Unity .
  2. Aggiungi il FirebaseFunctions.unitypackage dall'SDK Firebase Unity al tuo progetto Unity.

Inizializza l'SDK del client

Inizializza un'istanza di Cloud Functions:

Veloce

lazy var functions = Functions.functions()

Obiettivo-C

@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];

API con spazio dei nomi 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();

API modulare Web

const app = initializeApp({
  projectId: '### CLOUD FUNCTIONS PROJECT ID ###',
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
});
const functions = getFunctions(app);

Kotlin+KTX

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);

Unità

functions = Firebase.Functions.DefaultInstance;

Chiama la funzione

Veloce

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
  }
}

Obiettivo-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"];
}];

API con spazio dei nomi Web

var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
  .then((result) => {
    // Read result of the Cloud Function.
    var sanitizedMessage = result.data.text;
  });

API modulare 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+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
        }
}

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);
}

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;
  });
}

Gestire 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, message e details dall'errore del server. Altrimenti l'errore contiene il messaggio INTERNAL e il codice INTERNAL . Consulta le indicazioni su come gestire gli errori nella funzione richiamabile.

Veloce

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 isEqual:@"com.firebase.functions"]) {
    FIRFunctionsErrorCode code = error.code;
    NSString *message = error.localizedDescription;
    NSObject *details = error.userInfo[@"details"];
  }
  // ...
}

API con spazio dei nomi 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;
    // ...
  });

API modulare 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+KTX

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);
  // ...

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;
  }
});

Prima di avviare l'app, devi abilitare App Check per garantire che solo le tue app possano accedere agli endpoint delle funzioni richiamabili.