Wywoływanie funkcji z aplikacji (1 generacji)

Pakiety SDK klienta Cloud Functions for Firebase umożliwiają wywoływanie funkcji bezpośrednio z aplikacji w Firebase. Aby wywołać funkcję z aplikacji w ten sposób, napisz i wdroż funkcję wywoływaną przez HTTP w Cloud Functions, a następnie dodaj logikę klienta, aby wywołać funkcję z aplikacji.

Pamiętaj, że funkcje wywoływane przez HTTP są podobne do funkcji HTTP, ale nie są z nimi identyczne. Aby używać funkcji wywoływanych przez HTTP, musisz używać pakietu SDK klienta dla swojej platformy wraz z interfejsem API backendu (lub zaimplementować protokół). Funkcje wywoływalne różnią się od funkcji HTTP tym, że:

  • W przypadku funkcji wywoływalnych tokeny Firebase Authentication, FCM i App Check (jeśli są dostępne) są automatycznie dołączane do żądań.
  • Aktywator automatycznie deserializuje treść żądania i weryfikuje tokeny uwierzytelniania.

Pakiet SDK Firebase dla Cloud Functions 2 generacji i nowszych współpracuje z tymi minimalnymi wersjami pakietów SDK klienta Firebase, aby obsługiwać funkcje wywoływane przez HTTPS:

  • Firebase SDK na platformy Apple 13.1.0
  • Firebase SDK for Android 23.0.0
  • Modułowy pakiet SDK Firebase dla aplikacji internetowych w wersji 9.7.0

Jeśli chcesz dodać podobną funkcję do aplikacji utworzonej na nieobsługiwanej platformie, zapoznaj się ze specyfikacją protokołu https.onCall. W dalszej części tego przewodnika znajdziesz instrukcje pisania, wdrażania i wywoływania funkcji wywoływanej przez HTTP na platformach Apple, Android, internetowych, C++ i Unity.

Pisanie i wdrażanie funkcji możliwej do wywołania

Użyj functions.https.onCall, aby utworzyć funkcję wywoływaną przez HTTPS. Ta metoda przyjmuje 2 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) => {
    // ...
  });
  

W przypadku funkcji wywoływanej, która zapisuje wiadomość tekstową w Realtime Database, data może zawierać tekst wiadomości, a parametry context reprezentują informacje uwierzytelniające użytkownika:

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

Odległość między lokalizacją funkcji wywoływalnej a lokalizacją klienta wywołującego może powodować opóźnienia sieci. Aby zoptymalizować wydajność, rozważ określenie lokalizacji funkcji, jeśli ma to zastosowanie, i upewnij się, że lokalizacja funkcji wywoływanej jest zgodna z lokalizacją ustawioną podczas inicjowania pakietu SDK po stronie klienta.

Opcjonalnie możesz dołączyć atest App Check, aby chronić zasoby backendu przed nadużyciami, takimi jak oszukańcze płatności czy phishing. Zobacz Włączanie egzekwowania App Check w Cloud Functions.

Wysyłanie wyniku z powrotem

Aby wysłać dane z powrotem do klienta, zwróć dane, które można zakodować 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 obietnicę są wysyłane z powrotem do klienta. Możesz na przykład zwrócić oczyszczony tekst, który funkcja wywoływalna zapisała w 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};
})

Obsługuj błędy

Aby klient otrzymał przydatne informacje o błędzie, zwróć błędy z funkcji wywoływanej, zgłaszając (lub zwracając odrzuconą obietnicę) instancję functions.https.HttpsError. Błąd ma atrybut code, który może mieć jedną z wartości wymienionych na stronie functions.https.HttpsError. Błędy zawierają też ciąg znaków message, który domyślnie jest pusty. Mogą też mieć opcjonalne pole details z dowolną wartością. Jeśli funkcje zgłoszą błąd inny niż HttpsError, klient otrzyma błąd z komunikatem INTERNAL i kodem internal.

Na przykład funkcja może zgłaszać błędy weryfikacji danych i uwierzytelniania z komunikatami o błędach, które są zwracane 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 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.");
}

Wdrażanie funkcji możliwej do wywołania

Po zapisaniu ukończonej funkcji wywoływalnej w index.js jest ona wdrażana wraz ze wszystkimi innymi funkcjami, gdy uruchamiasz firebase deploy. Aby wdrożyć tylko funkcję wywoływalną, użyj argumentu --only, jak pokazano poniżej, aby przeprowadzić wdrożenie częściowe:

firebase deploy --only functions:addMessage

Jeśli podczas wdrażania funkcji wystąpią błędy uprawnień, upewnij się, że użytkownikowi, który uruchamia polecenia wdrażania, przypisano odpowiednie role uprawnień.

Konfigurowanie środowiska programistycznego klienta

Upewnij się, że spełniasz wszystkie wymagania wstępne, a następnie dodaj do aplikacji wymagane zależności i biblioteki klienta.

iOS+

Postępuj zgodnie z instrukcjami, aby dodać Firebase do aplikacji na urządzenia Apple.

Do instalowania zależności Firebase i zarządzania nimi używaj menedżera pakietów Swift.

  1. W Xcode, gdy projekt aplikacji jest otwarty, kliknij File > Add Packages (Plik > Dodaj pakiety).
  2. Gdy pojawi się prośba, dodaj repozytorium pakietu SDK Firebase na platformy Apple:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Wybierz bibliotekę Cloud Functions.
  5. Dodaj flagę -ObjC do sekcji Other Linker Flags (Inne flagi łączące) w ustawieniach kompilacji celu.
  6. Gdy skończysz, Xcode zacznie automatycznie przetwarzać i pobierać zależności w tle.

Web

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do aplikacji internetowej. Pamiętaj, aby uruchomić w terminalu to polecenie:
    npm install firebase@13.1.0 --save
  2. Ręcznie zażądaj zarówno Firebase Core, jak i 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

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do aplikacji internetowej.
  2. Dodaj do aplikacji podstawowe biblioteki klienta Firebase i 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>

Pakiet SDK Cloud Functions jest też dostępny jako pakiet npm.

  1. Uruchom w terminalu to polecenie:
    npm install firebase@8.10.1 --save
  2. Ręcznie zażądaj zarówno Firebase Core, jak i Cloud Functions:
    const firebase = require("firebase");
    // Required for side-effects
    require("firebase/functions");

Kotlin

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do aplikacji na Androida.

  2. W pliku Gradle modułu (na poziomie aplikacji) (zwykle <project>/<app-module>/build.gradle.kts lub <project>/<app-module>/build.gradle) dodaj zależność z biblioteką Cloud Functions na Androida. Zalecamy używanie Firebase Android BoM do kontrolowania obsługi wersji biblioteki.

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

    Gdy korzystasz z Firebase Android BoM, aplikacja zawsze używa zgodnych wersji bibliotek Firebase na Androida.

    (Alternatywa)  Dodaj zależności biblioteki Firebase bez używania BoM

    Jeśli nie zdecydujesz się na użycie Firebase BoM, musisz określić każdą wersję biblioteki Firebase w jej wierszu zależności.

    Jeśli w aplikacji używasz kilku bibliotek Firebase, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewni zgodność wszystkich wersji.

    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:23.0.0")
    }

Java

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do aplikacji na Androida.

  2. W pliku Gradle modułu (na poziomie aplikacji) (zwykle <project>/<app-module>/build.gradle.kts lub <project>/<app-module>/build.gradle) dodaj zależność z biblioteką Cloud Functions na Androida. Zalecamy używanie Firebase Android BoM do kontrolowania obsługi wersji biblioteki.

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

    Gdy korzystasz z Firebase Android BoM, aplikacja zawsze używa zgodnych wersji bibliotek Firebase na Androida.

    (Alternatywa)  Dodaj zależności biblioteki Firebase bez używania BoM

    Jeśli nie zdecydujesz się na użycie Firebase BoM, musisz określić każdą wersję biblioteki Firebase w jej wierszu zależności.

    Jeśli w aplikacji używasz kilku bibliotek Firebase, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewni zgodność wszystkich wersji.

    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:23.0.0")
    }

Dart

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do aplikacji Flutter.

  2. Aby zainstalować wtyczkę, uruchom to polecenie z katalogu głównego projektu Flutter:

    flutter pub add cloud_functions
    
  3. Gdy to zrobisz, ponownie skompiluj aplikację Flutter:

    flutter run
    
  4. Po zainstalowaniu wtyczki cloud_functions możesz uzyskać do niej dostęp, importując ją w kodzie Dart:

    import 'package:cloud_functions/cloud_functions.dart';
    

C++

W przypadku C++ na Androidzie:

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do projektu w C++.
  2. Dodaj bibliotekę firebase_functions do pliku CMakeLists.txt.

W przypadku C++ na platformach Apple:

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do projektu w C++.
  2. Dodaj pod Cloud Functions do Podfile:
    pod 'Firebase/Functions'
  3. Zapisz plik, a następnie uruchom:
    pod install
  4. Dodaj do projektu Xcode platformy Firebase Core i Cloud Functions z pakietu SDK Firebase C++.
    • firebase.framework
    • firebase_functions.framework

Unity

  1. Postępuj zgodnie z instrukcjami, aby dodać Firebase do projektu Unity.
  2. Dodaj FirebaseFunctions.unitypackage z pakietu SDK Firebase Unity do projektu Unity.

Inicjowanie pakietu SDK klienta

Zainicjuj instancję 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;

Wywoływanie funkcji

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

Obsługa błędów po stronie klienta

Klient otrzymuje błąd, jeśli serwer zgłosił błąd lub jeśli wynikowa obietnica została odrzucona.

Jeśli błąd zwrócony przez funkcję jest typu function.https.HttpsError, klient otrzymuje błąd code, message i details z błędu serwera. W przeciwnym razie błąd zawiera komunikat INTERNAL i kod INTERNAL. Dowiedz się, jak obsługiwać błędy w funkcji wywoływalnej.

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

Ustawianie czasu oczekiwania klienta

Domyślnie pakiety SDK klienta Cloud Functions używają 70-sekundowego limitu czasu dla żądań wywoływalnych. Jeśli wykonanie funkcji wywoływalnej trwa dłużej niż 70 sekund, pakiet SDK klienta kończy żądanie z błędem DEADLINE_EXCEEDED (deadline-exceeded) – nawet jeśli skonfigurowano dłuższy czas oczekiwania po stronie serwera.

Aby obsługiwać długotrwałe funkcje wywoływalne, musisz zwiększyć limit czasu oczekiwania zarówno na serwerze, jak i na kliencie:

  1. Zwiększ limit czasu oczekiwania funkcji po stronie serwera (patrz Ustawianie limitu czasu oczekiwania i alokacji pamięci).
  2. Zwiększ limit czasu po stronie klienta podczas konfigurowania odwołania do funkcji wywoływanej w aplikacji:

Swift

let callable = functions.httpsCallable("addMessage")
callable.timeoutInterval = 300  // 300 seconds (default is 70)
let result = try await callable.call(["text": text, "push": true])

Objective-C

FIRHTTPSCallable *callable = [self.functions HTTPSCallableWithName:@"addMessage"];
callable.timeoutInterval = 300;  // 300 seconds (default is 70)
[callable callWithObject:@{@"text": text, @"push": @YES}
              completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
  // ...
}];

Web

var addMessage = firebase.functions().httpsCallable('addMessage', {
  timeout: 300000,  // 300 seconds in milliseconds (default is 70000)
});
addMessage({ text: messageText })
  .then((result) => {
    // ...
  });

Web

import { getFunctions, httpsCallable } from "firebase/functions";

const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage', {
  timeout: 300000,  // 300 seconds in milliseconds (default is 70000)
});
const result = await addMessage({ text: messageText });

Kotlin

val callable = functions.getHttpsCallable("addMessage")
callable.setTimeout(300L, TimeUnit.SECONDS)
val result = callable.call(data).await()

Java

HttpsCallableReference callable = mFunctions.getHttpsCallable("addMessage");
callable.setTimeout(300L, TimeUnit.SECONDS);
Task<HttpsCallableResult> result = callable.call(data);

Dart

final callable = FirebaseFunctions.instance.httpsCallable(
  'addMessage',
  options: HttpsCallableOptions(
    timeout: const Duration(seconds: 300),
  ),
);
final result = await callable.call({
  'text': text,
  'push': true,
});

Zalecane: zapobieganie nadużyciom za pomocą App Check

Przed uruchomieniem aplikacji włącz App Check, aby mieć pewność, że tylko Twoje aplikacje będą miały dostęp do punktów końcowych funkcji wywoływalnych.