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

Gli esempi di codice in questa sezione si basano su un esempio di avvio rapido completo che dimostra come inviare richieste a una funzione lato server e ottenere una risposta utilizzando uno degli SDK client. Per iniziare, importa i moduli richiesti:

Node.js

// Dependencies for callable functions.
const {onCall, HttpsError} = require("firebase-functions/v2/https");
const {logger} = require("firebase-functions/v2");

// Dependencies for the addMessage function.
const {getDatabase} = require("firebase-admin/database");
const sanitizer = require("./sanitizer");

Pitone

# Dependencies for callable functions.
from firebase_functions import https_fn, options

# Dependencies for writing to Realtime Database.
from firebase_admin import db, initialize_app

Utilizza il gestore delle richieste per la tua piattaforma ( functions.https.onCall ) o on_call ) per creare una funzione richiamabile HTTPS. Questo metodo accetta un parametro di richiesta:

Node.js

// Saves a message to the Firebase Realtime Database but sanitizes the
// text by removing swearwords.
exports.addmessage = onCall((request) => {
  // ...
});

Pitone

@https_fn.on_call()
def addmessage(req: https_fn.CallableRequest) -> Any:
    """Saves a message to the Firebase Realtime Database but sanitizes the text
    by removing swear words."""

Il parametro request contiene i dati passati dall'app client nonché un contesto aggiuntivo come lo stato di autenticazione. Per una funzione richiamabile che salva un messaggio di testo nel Realtime Database, ad esempio, data potrebbero contenere il testo del messaggio, insieme alle informazioni di autenticazione in auth :

Node.js

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

Pitone

# Message text passed from the client.
text = req.data["text"]
# Authentication / user information is automatically added to the request.
uid = req.auth.uid
name = req.auth.token.get("name", "")
picture = req.auth.token.get("picture", "")
email = req.auth.token.get("email", "")

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:

Node.js

// returning result.
return {
  firstNumber: firstNumber,
  secondNumber: secondNumber,
  operator: "+",
  operationResult: firstNumber + secondNumber,
};

Pitone

return {
    "firstNumber": first_number,
    "secondNumber": second_number,
    "operator": "+",
    "operationResult": first_number + second_number
}

Il testo ripulito dall'esempio di testo del messaggio viene restituito sia al client che al Realtime Database. In Node.js, questo può essere fatto in modo asincrono utilizzando una promessa JavaScript:

Node.js

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

Pitone

# Saving the new message to the Realtime Database.
sanitized_message = sanitize_text(text)  # Sanitize message.
db.reference("/messages").push({  # type: ignore
    "text": sanitized_message,
    "author": {
        "uid": uid,
        "name": name,
        "picture": picture,
        "email": email
    }
})
print("New message written")

# Returning the sanitized message to the client.
return {"text": sanitized_message}

Configurare CORS (condivisione di risorse multiorigine)

Utilizza l'opzione cors per controllare quali origini possono accedere alla tua funzione.

Per impostazione predefinita, le funzioni richiamabili hanno CORS configurato per consentire richieste da tutte le origini. Per consentire alcune richieste multiorigine, ma non tutte, passa un elenco di domini specifici o espressioni regolari che dovrebbero essere consentite. Per esempio:

Node.js

const { onCall } = require("firebase-functions/v2/https");

exports.getGreeting = onCall(
  { cors: [/firebase\.com$/, "flutter.com"] },
  (request) => {
    return "Hello, world!";
  }
);

Per vietare le richieste multiorigine, imposta la policy cors su false .

Gestire gli errori

Per garantire che il client ottenga dettagli utili sull'errore, restituire gli errori da un richiamabile lanciando (o per Node.js restituendo una Promise rifiutata con) un'istanza functions.https.HttpsError o https_fn.HttpsError . L'errore ha un attributo code che può essere uno dei valori elencati in codici di stato gRPC. 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 un errore HTTPS, 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:

Node.js

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

Pitone

# Checking attribute.
if not isinstance(text, str) or len(text) < 1:
    # Throwing an HttpsError so that the client gets the error details.
    raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.INVALID_ARGUMENT,
                              message=('The function must be called with one argument, "text",'
                                       " containing the message text to add."))

# Checking that the user is authenticated.
if req.auth is None:
    # Throwing an HttpsError so that the client gets the error details.
    raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.FAILED_PRECONDITION,
                              message="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);
    

Androide

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

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

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.