Gọi các hàm qua ứng dụng

SDK ứng dụng Cloud Functions for Firebase cho phép bạn gọi các hàm trực tiếp từ một ứng dụng Firebase. Để gọi một hàm từ ứng dụng của bạn theo cách này, hãy viết và triển khai một hàm HTTP có thể gọi trong Cloud Functions, sau đó thêm logic ứng dụng để gọi hàm từ ứng dụng của bạn.

Bạn cần lưu ý rằng các hàm có thể gọi qua HTTP tương tự nhưng không giống với các hàm HTTP. Để sử dụng các hàm có thể gọi qua HTTP, bạn phải sử dụng SDK ứng dụng cho nền tảng của mình cùng với API phụ trợ (hoặc triển khai giao thức). Hàm có thể gọi có những điểm khác biệt chính sau đây so với hàm HTTP:

  • Với các hàm có thể gọi, mã thông báo Firebase Authentication, mã thông báo FCM và mã thông báo App Check (nếu có) sẽ tự động được đưa vào các yêu cầu.
  • Trình kích hoạt tự động giải tuần tự hoá nội dung yêu cầu và xác thực mã thông báo xác thực.

SDK Firebase cho Cloud Functions thế hệ thứ 2 trở lên tương thích với các phiên bản SDK ứng dụng Firebase tối thiểu sau đây để hỗ trợ các hàm có thể gọi qua HTTPS:

  • SDK Firebase cho nền tảng Apple 13.0.0
  • SDK Firebase cho Android 23.0.0
  • Firebase Modular Web SDK phiên bản 9.7.0

Nếu bạn muốn thêm chức năng tương tự vào một ứng dụng được xây dựng trên một nền tảng không được hỗ trợ, hãy xem Thông số kỹ thuật của giao thức cho https.onCall. Phần còn lại của hướng dẫn này cung cấp hướng dẫn về cách viết, triển khai và gọi một hàm có thể gọi HTTP cho các nền tảng của Apple, Android, web, C++ và Unity.

Viết và triển khai hàm có thể gọi

Các ví dụ về mã trong phần này dựa trên một mẫu bắt đầu nhanh hoàn chỉnh, minh hoạ cách gửi yêu cầu đến một hàm phía máy chủ và nhận phản hồi bằng một trong các SDK ứng dụng. Để bắt đầu, hãy nhập các mô-đun bắt buộc:

Node.js

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

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

Python

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

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

Dart (thử nghiệm)

// Dependencies for callable functions.
import 'package:firebase_functions/firebase_functions.dart';

Sử dụng trình xử lý yêu cầu cho nền tảng của bạn để tạo một hàm có thể gọi HTTPS. Phương thức này sử dụng một tham số yêu cầu:

Node.js

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

Python

@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."""

Dart (thử nghiệm)

// Adds two numbers to each other.
firebase.https.onCall(name: 'addNumbers', (request, response) async {

Tham số request chứa dữ liệu được truyền từ ứng dụng khách cũng như bối cảnh bổ sung như trạng thái xác thực. Ví dụ: đối với một hàm có thể gọi để lưu tin nhắn văn bản vào Realtime Database, data có thể chứa văn bản tin nhắn cùng với thông tin xác thực trong 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;

Python

# 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", "")

Dart (thử nghiệm)

// Numbers passed from the client.
final data = request.data as Map<String, Object?>?;
final firstNumber = data?['firstNumber'];
final secondNumber = data?['secondNumber'];
// Authentication / user information is automatically added to the request.
final uid = request.auth?.uid;
final token = request.auth?.token;
final name = token?['name'];
final picture = token?['picture'];
final email = token?['email'];

// Use variables to suppress 'unused' lint warnings
print(
  'User details: uid=$uid, name=$name, picture=$picture, email=$email',
);

Khoảng cách giữa vị trí của hàm có thể gọi và vị trí của ứng dụng gọi có thể tạo ra độ trễ mạng. Để tối ưu hoá hiệu suất, hãy cân nhắc việc chỉ định vị trí hàm nếu có thể và đảm bảo điều chỉnh vị trí của hàm có thể gọi cho phù hợp với vị trí được đặt khi bạn khởi chạy SDK ở phía máy khách.

Nếu muốn, bạn có thể đính kèm một chứng thực App Check để giúp bảo vệ tài nguyên phụ trợ của bạn khỏi hành vi sai trái, chẳng hạn như lừa đảo qua giao dịch thanh toán hoặc lừa đảo. Xem phần Bật chế độ thực thi App Check cho Cloud Functions.

Gửi lại kết quả

Để gửi dữ liệu trở lại ứng dụng, hãy trả về dữ liệu có thể được mã hoá JSON. Ví dụ: để trả về kết quả của phép cộng:

Node.js

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

Python

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

Dart (thử nghiệm)

// returning result.
return CallableResult({
  'firstNumber': firstNumber,
  'secondNumber': secondNumber,
  'operator': '+',
  'operationResult': firstNumber + secondNumber,
});

Văn bản đã dọn dẹp từ ví dụ về văn bản thông báo sẽ được trả về cho cả ứng dụng khách và Realtime Database. Trong Node.js, bạn có thể thực hiện việc này bằng cách không đồng bộ bằng lời hứa 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};
})

Python

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

Hàm của bạn phải trả về một giá trị hoặc trong trường hợp Node.js, một Promise phân giải bằng một giá trị. Nếu không, hàm có thể chấm dứt trước khi dữ liệu được gửi lại cho ứng dụng. Hãy xem phần Chấm dứt hàm để biết hướng dẫn.

Gửi và nhận kết quả truyền trực tuyến

Hàm có thể gọi có cơ chế xử lý kết quả truyền trực tuyến. Nếu có trường hợp sử dụng yêu cầu truyền trực tuyến, bạn có thể định cấu hình tính năng truyền trực tuyến trong yêu cầu có thể gọi, sau đó sử dụng phương thức thích hợp từ SDK ứng dụng để gọi hàm.

Gửi kết quả phát trực tuyến

Để truyền trực tuyến một cách hiệu quả các kết quả được tạo theo thời gian, chẳng hạn như từ một số yêu cầu API riêng biệt hoặc API AI tạo sinh, hãy kiểm tra thuộc tính acceptsStreaming trên yêu cầu có thể gọi của bạn. Khi đặt thuộc tính này thành true, bạn có thể truyền trực tuyến kết quả trở lại ứng dụng bằng response.sendChunk().

Ví dụ: nếu một ứng dụng cần truy xuất dữ liệu dự báo thời tiết cho nhiều vị trí, thì hàm có thể gọi có thể gửi riêng thông tin dự báo của từng vị trí đến những ứng dụng khách đã yêu cầu phản hồi truyền trực tuyến, thay vì khiến các ứng dụng khách đó phải đợi cho đến khi tất cả yêu cầu dự báo đều được giải quyết:

exports.getForecast = onCall(async (request, response) => {
  if (request.data?.locations?.length < 1) {
    throw new HttpsError("invalid-argument", "Missing locations to forecast");
  }

  // fetch forecast data for all requested locations
  const allRequests = request.data.locations.map(
      async ({latitude, longitude}) => {
        const forecast = await weatherForecastApi(latitude, longitude);
        const result = {latitude, longitude, forecast};

        // clients that support streaming will have each
        // forecast streamed to them as they complete
        if (request.acceptsStreaming) {
          response.sendChunk(result);
        }

        return result;
      },
  );

  // Return the full set of data to all clients
  return Promise.all(allRequests);
});

Xin lưu ý rằng cách hoạt động của response.sendChunk() phụ thuộc vào một số chi tiết nhất định trong yêu cầu của ứng dụng:

  1. Nếu ứng dụng yêu cầu phản hồi trực tuyến: response.sendChunk(data) sẽ gửi ngay phần dữ liệu.

  2. Nếu ứng dụng không yêu cầu phản hồi trực tuyến: response.sendChunk() sẽ không làm gì cho lệnh gọi đó. Câu trả lời đầy đủ sẽ được gửi sau khi tất cả dữ liệu đã sẵn sàng.

Để xác định xem ứng dụng có đang yêu cầu phản hồi trực tuyến hay không, hãy kiểm tra thuộc tính request.acceptsStreaming. Ví dụ: nếu request.acceptsStreaming là false, bạn có thể quyết định bỏ qua mọi công việc tốn nhiều tài nguyên liên quan cụ thể đến việc chuẩn bị hoặc gửi từng đoạn riêng lẻ, vì ứng dụng không mong đợi một quá trình phân phối gia tăng.

Nhận kết quả truyền trực tuyến

Trong trường hợp thông thường, ứng dụng khách yêu cầu truyền trực tuyến bằng phương thức .stream, sau đó lặp lại các kết quả:

Swift

func listenToWeatherForecast() async throws {
    isLoading = true
    defer { isLoading = false }

    Functions
      .functions(region: "us-central1")
    let getForecast: Callable<WeatherRequest, StreamResponse<WeatherResponse, [WeatherResponse]>> = Functions.functions().httpsCallable("getForecast")

    let request = WeatherRequest(locations: locations)
    let stream = try getForecast.stream(request)

    for try await response in stream {
      switch response {
      case .message(let singleResponse):
        weatherData["\(singleResponse.latitude),\(singleResponse.longitude)"] = singleResponse
      case .result(let arrayOfResponses):
        for response in arrayOfResponses {
          weatherData["\(response.latitude),\(response.longitude)"] = response
        }
        print("Stream ended.")
        return
      }
    }
  }

Web

// Get the callable by passing an initialized functions SDK.
const getForecast = httpsCallable(functions, "getForecast");

// Call the function with the `.stream()` method to start streaming.
const { stream, data } = await getForecast.stream({
  locations: favoriteLocations,
});

// The `stream` async iterable returned by `.stream()`
// will yield a new value every time the callable
// function calls `sendChunk()`.
for await (const forecastDataChunk of stream) {
  // update the UI every time a new chunk is received
  // from the callable function
  updateUi(forecastDataChunk);
}

// The `data` promise resolves when the callable
// function completes.
const allWeatherForecasts = await data;
finalizeUi(allWeatherForecasts);

Lặp lại thông qua đối tượng lặp không đồng bộ stream như minh hoạ. Việc chờ đợi lời hứa data cho ứng dụng biết rằng yêu cầu đã hoàn tất

Kotlin

// Get the callable by passing an initialized functions SDK.
val getForecast = functions.getHttpsCallable("getForecast");

// Call the function with the `.stream()` method and convert it to a flow
getForecast.stream(
  mapOf("locations" to favoriteLocations)
).asFlow().collect { response ->
  when (response) {
    is StreamResponse.Message -> {
      // The flow will emit a [StreamResponse.Message] value every time the
      // callable function calls `sendChunk()`.
      val forecastDataChunk = response.message.data as Map<String, Any>
      // Update the UI every time a new chunk is received
      // from the callable function
      updateUI(
        forecastDataChunk["latitude"] as Double,
        forecastDataChunk["longitude"] as Double,
        forecastDataChunk["forecast"] as Double,
      )
    }
    is StreamResponse.Result -> {
      // The flow will emit a [StreamResponse.Result] value when the
      // callable function completes.
      val allWeatherForecasts = response.result.data as List<Map<String, Any>>
      finalizeUI(allWeatherForecasts)
    }
  }
}

Để sử dụng hàm tiện ích asFlow(), hãy thêm thư viện org.jetbrains.kotlinx:kotlinx-coroutines-reactive làm phần phụ thuộc vào tệp build.gradle(.kts) của ứng dụng.

Java

// Get the callable by passing an initialized functions SDK.
HttpsCallableReference getForecast = mFunctions.getHttpsCallable("getForecast");
getForecast.stream(
  new HashMap<String, Object>() {{
    put("locations", favoriteLocations);
  }}
).subscribe(new Subscriber<StreamResponse>() {
  @Override
  public void onSubscribe(Subscription subscription) {
    subscription.request(Long.MAX_VALUE);
  }

  @Override
  public void onNext(StreamResponse streamResponse) {
    if (streamResponse instanceof StreamResponse.Message) {
      // The flow will emit a [StreamResponse.Message] value every time the
      // callable function calls `sendChunk()`.
      StreamResponse.Message response = (StreamResponse.Message) streamResponse;
      Map<String, Object> forecastDataChunk =
        (Map<String, Object>) response.getMessage().getData();
      // Update the UI every time a new chunk is received
      // from the callable function
      updateUI(
        (double) forecastDataChunk.get("latitude"),
        (double) forecastDataChunk.get("longitude"),
        (double) forecastDataChunk.get("forecast")
      );
    } else if(streamResponse instanceof StreamResponse.Result) {
      // The flow will emit a [StreamResponse.Result] value when the
      // callable function completes.
      StreamResponse.Result response = (StreamResponse.Result) streamResponse;
      List<Map<String, Object>> allWeatherForecasts =
        (List<Map<String, Object>>) response.getResult().getData();
      finalizeUI();
    }
  }

  @Override
  public void onError(Throwable throwable) {
    // an error occurred in the function
  }

  @Override
  public void onComplete() {

  }
});

Định cấu hình CORS (Chia sẻ tài nguyên khác nguồn gốc)

Sử dụng tuỳ chọn cors để kiểm soát những nguồn gốc nào có thể truy cập vào hàm của bạn.

Theo mặc định, các hàm có thể gọi có CORS được định cấu hình để cho phép các yêu cầu từ tất cả nguồn gốc. Để cho phép một số yêu cầu trên nhiều nguồn gốc, nhưng không phải tất cả, hãy truyền danh sách các miền hoặc biểu thức chính quy cụ thể cần được cho phép. Ví dụ:

Node.js

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

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

Python

from firebase_functions import https_fn, options

@https_fn.on_call(
    cors=options.CorsOptions(
        cors_origins=[r"firebase\.com$", r"https://flutter\.com"],
        cors_methods=["get", "post"],
    )
)
def say_hello(req: https_fn.CallableRequest) -> Any:
    return "Hello world!"

Dart (thử nghiệm)

import 'package:firebase_functions/firebase_functions.dart';

void main(List<String> args) {
  fireUp(args, (firebase) {
    firebase.https.onCall(
      name: 'getGreeting',
      options: CallableOptions(
        cors: Cors([RegExp(r'^https:\/\/firebase\.com$'), 'https://flutter.com']),
      ),
      (request) async {
        return CallableResult('Hello, world!');
      },
    );
  });
}

Để cấm các yêu cầu khác nguồn gốc, hãy đặt chính sách cors thành false.

Xử lý lỗi

Để đảm bảo ứng dụng nhận được thông tin chi tiết hữu ích về lỗi, hãy trả về lỗi từ một hàm có thể gọi bằng cách gửi (hoặc đối với Node.js, trả về một Promise bị từ chối) một thực thể của functions.https.HttpsError hoặc https_fn.HttpsError. Lỗi này có một thuộc tính code có thể là một trong các giá trị được liệt kê trong Mã trạng thái gRPC. Lỗi cũng có một chuỗi message, mặc định là một chuỗi trống. Các sự kiện này cũng có thể có một trường details không bắt buộc với một giá trị tuỳ ý. Nếu một lỗi không phải lỗi HTTPS được gửi từ các hàm của bạn, thì ứng dụng sẽ nhận được lỗi kèm theo thông báo INTERNAL và mã internal.

Ví dụ: một hàm có thể gửi lỗi xác thực dữ liệu và lỗi xác thực kèm theo thông báo lỗi để trả về cho ứng dụng gọi:

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

Python

# 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.",
    )

Dart (thử nghiệm)

// Checking that attributes are present and are numbers.
if (firstNumber is! num || secondNumber is! num) {
  // Throwing an HttpsError so that the client gets the error details.
  throw InvalidArgumentError(
    'The function must be called with two arguments "firstNumber" and "secondNumber" which must both be numbers.',
  );
}

Triển khai hàm có thể gọi

Sau khi bạn lưu một hàm có thể gọi đã hoàn tất trong index.js, hàm đó sẽ được triển khai cùng với tất cả các hàm khác khi bạn chạy firebase deploy. Để chỉ triển khai hàm có thể gọi, hãy sử dụng đối số --only như minh hoạ để thực hiện triển khai một phần:

firebase deploy --only functions:addMessage

Nếu bạn gặp lỗi về quyền khi triển khai các hàm, hãy đảm bảo rằng vai trò IAM thích hợp được chỉ định cho người dùng chạy lệnh triển khai.

Thiết lập môi trường phát triển ứng dụng khách

Đảm bảo bạn đáp ứng mọi điều kiện tiên quyết, sau đó thêm các phần phụ thuộc và thư viện ứng dụng cần thiết vào ứng dụng của bạn.

iOS+

Làm theo hướng dẫn để thêm Firebase vào ứng dụng Apple.

Sử dụng Trình quản lý gói Swift để cài đặt và quản lý các phần phụ thuộc của Firebase.

  1. Trong Xcode, khi dự án ứng dụng của bạn đang mở, hãy chuyển đến File > Add Packages (Tệp > Thêm gói).
  2. Khi được nhắc, hãy thêm kho lưu trữ SDK Firebase cho nền tảng của Apple:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Chọn thư viện Cloud Functions.
  5. Thêm cờ -ObjC vào phần Other Linker Flags (Cờ trình liên kết khác) trong chế độ cài đặt bản dựng của mục tiêu.
  6. Khi hoàn tất, Xcode sẽ tự động bắt đầu phân giải và tải các phần phụ thuộc của bạn xuống ở chế độ nền.

Web

  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng web của bạn. Hãy nhớ chạy lệnh sau từ thiết bị đầu cuối:
    npm install firebase@13.0.0 --save
  2. Yêu cầu cả Firebase Core và Cloud Functions theo cách thủ công:

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

Android

  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng Android của bạn.

  2. Trong tệp Gradle (ở cấp ứng dụng) trong mô-đun (thường là <project>/<app-module>/build.gradle.kts hoặc <project>/<app-module>/build.gradle), hãy thêm phần phụ thuộc cho thư viện Cloud Functions dành cho Android. Bạn nên sử dụng Firebase Android BoM để kiểm soát việc tạo phiên bản thư viện.

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

    Bằng cách sử dụng Firebase Android BoM, ứng dụng của bạn sẽ luôn sử dụng những phiên bản tương thích của thư viện Android trên Firebase.

    (Cách khác)  Thêm phần phụ thuộc thư viện Firebase mà không sử dụng BoM

    Nếu chọn không sử dụng Firebase BoM, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phần phụ thuộc của phiên bản đó.

    Xin lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng, bạn nên sử dụng BoM để quản lý các phiên bản thư viện, nhằm đảm bảo rằng tất cả phiên bản đều tương thích.

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

Khởi chạy SDK ứng dụng

Khởi động một thực thể của Cloud Functions:

Swift

lazy var functions = Functions.functions()

Objective-C

@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions 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();

Gọi hàm

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

Xử lý lỗi trên ứng dụng khách

Ứng dụng sẽ nhận được lỗi nếu máy chủ gửi lỗi hoặc nếu lời hứa kết quả bị từ chối.

Nếu lỗi do hàm trả về thuộc loại function.https.HttpsError, thì ứng dụng sẽ nhận được lỗi code, message và details từ lỗi phía máy chủ. Nếu không, lỗi sẽ chứa thông báo INTERNAL và mã INTERNAL. Xem hướng dẫn về cách xử lý lỗi trong hàm có thể gọi.

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

Đặt thời gian chờ của ứng dụng khách

Theo mặc định, SDK ứng dụng Cloud Functions sử dụng thời gian chờ 70 giây cho các yêu cầu có thể gọi. Nếu một hàm có thể gọi mất hơn 70 giây để hoàn tất, thì SDK ứng dụng sẽ chấm dứt yêu cầu kèm theo lỗi DEADLINE_EXCEEDED (deadline-exceeded), ngay cả khi bạn đã định cấu hình thời gian chờ phía máy chủ dài hơn.

Để hỗ trợ các hàm có thể gọi chạy trong thời gian dài, bạn phải tăng thời gian chờ trên cả máy chủ và máy khách:

  1. Tăng thời gian chờ của hàm phía máy chủ (xem phần Đặt thời gian chờ và phân bổ bộ nhớ).
  2. Tăng thời gian chờ phía máy khách khi định cấu hình tham chiếu có thể gọi trong ứng dụng:

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

Nên dùng: Ngăn chặn hành vi sai trái bằng App Check

Trước khi chạy ứng dụng, bạn nên bật App Check để đảm bảo rằng chỉ ứng dụng của bạn mới có thể truy cập vào các điểm cuối của hàm có thể gọi.