Gọi các chức năng từ ứng dụng của bạn


Chức năng đám mây dành cho SDK khách Firebase cho phép bạn gọi các chức năng trực tiếp 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 được trong Cloud Functions, sau đó thêm logic máy khách để gọi hàm từ ứng dụng của bạn.

Điều quan trọng cần lưu ý là các hàm có thể gọi 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 HTTP, bạn phải sử dụng SDK máy khách cho nền tảng của mình cùng với API phụ trợ (hoặc triển khai giao thức). Có thể gọi được có những điểm khác biệt chính so với các hàm HTTP:

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

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

  • SDK Firebase cho nền tảng Apple 10.19.0
  • SDK Firebase cho Android 20.4.0
  • SDK web mô-đun Firebase v. 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 nền tảng không được hỗ trợ, hãy xem Đặc tả 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 hàm có thể gọi HTTP cho nền tảng Apple, Android, web, C++ và Unity.

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

Sử dụng functions.https.onCall để tạo hàm có thể gọi HTTPS. Phương thức này có hai tham số: datacontext tùy chọn:

// Saves a message to the Firebase Realtime Database but sanitizes the text by removing swearwords.
exports.addMessage = functions.https.onCall((data, context) => {
  // ...
});

Ví dụ: đối với hàm có thể gọi để lưu tin nhắn văn bản vào Cơ sở dữ liệu thời gian thực, data có thể chứa văn bản tin nhắn, trong khi các tham số ngữ context biểu thị thông tin xác thực của người dùng:

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

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

Theo tùy chọn, bạn có thể đính kèm chứng thực Kiểm tra ứng dụng để giúp bảo vệ tài nguyên phụ trợ của bạn khỏi bị lạm dụng, chẳng hạn như gian lận thanh toán hoặc lừa đảo. Xem Bật thực thi Kiểm tra ứng dụng cho Chức năng đám mây .

Gửi lại kết quả

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

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

Để trả về dữ liệu sau một hoạt động không đồng bộ, hãy trả lại lời hứa. Dữ liệu được trả về bởi lời hứa sẽ được gửi lại cho khách hàng. Ví dụ: bạn có thể trả về văn bản đã được chọn lọc mà hàm có thể gọi được đã ghi vào Cơ sở dữ liệu thời gian thực:

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

Xử lý lỗi

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

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

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

Triển khai chức năng có thể gọi được

Sau khi bạn lưu một hàm có thể gọi đã hoàn thành 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 phần có thể gọi được, hãy sử dụng đối số --only như được hiển thị để thực hiện triển khai một phần :

firebase deploy --only functions:addMessage

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

Thiết lập môi trường phát triển khách hàng của bạn

Hãy đả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 cần thiết và thư viện ứng dụng khách 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 của bạn .

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 điều hướng đến File > Add Packages .
  2. Khi được nhắc, hãy thêm kho lưu trữ SDK nền tảng Firebase của Apple:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Chọn thư viện Chức năng đám mây.
  5. Thêm cờ -ObjC vào phần Cờ liên kết khác trong cài đặt bản dựng của mục tiêu của bạn.
  6. Khi hoàn tất, Xcode sẽ tự động bắt đầu phân giải và tải xuống các phần phụ thuộc của bạn ở chế độ nền.

API mô-đun web

  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng Web của bạn . Đảm bảo chạy lệnh sau từ thiết bị đầu cuối của bạn:
    npm install firebase@10.7.1 --save
    
  2. Yêu cầu thủ công cả lõi Firebase và Chức năng đám mây:

     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 không gian tên web

  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng Web của bạn .
  2. Thêm thư viện máy khách Firebase và Cloud Functions vào ứng dụng của bạn:
    <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>
    

SDK chức năng đám mây cũng có sẵn dưới dạng gói npm.

  1. Chạy lệnh sau từ thiết bị đầu cuối của bạn:
    npm install firebase@8.10.1 --save
    
  2. Yêu cầu thủ công cả lõi Firebase và Chức năng đám mây:
    const firebase = require("firebase");
    // Required for side-effects
    require("firebase/functions");
    

Kotlin+KTX

  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 mô-đun (cấp ứng dụng) của bạn (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 Chức năng đám mây thư viện dành cho Android. Chúng tôi khuyên bạn nên sử dụng BoM Android của Firebase để 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: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")
    }
    

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

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

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

    Lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng của mình, chúng tôi thực sự khuyên 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ả cá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:20.4.0")
    }
    
    Bạn đang tìm mô-đun thư viện dành riêng cho Kotlin? Bắt đầu từ tháng 10 năm 2023 (Firebase BoM 32.5.0) , cả nhà phát triển Kotlin và Java đều có thể phụ thuộc vào mô-đun thư viện chính (để biết chi tiết, hãy xem Câu hỏi thường gặp về sáng kiến ​​này ).

Java

  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 mô-đun (cấp ứng dụng) của bạn (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 Chức năng đám mây thư viện dành cho Android. Chúng tôi khuyên bạn nên sử dụng BoM Android của Firebase để 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: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")
    }
    

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

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

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

    Lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng của mình, chúng tôi thực sự khuyên 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ả cá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:20.4.0")
    }
    
    Bạn đang tìm mô-đun thư viện dành riêng cho Kotlin? Bắt đầu từ tháng 10 năm 2023 (Firebase BoM 32.5.0) , cả nhà phát triển Kotlin và Java đều có thể phụ thuộc vào mô-đun thư viện chính (để biết chi tiết, hãy xem Câu hỏi thường gặp về sáng kiến ​​này ).

Dart

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

  2. Từ thư mục gốc của dự án Flutter của bạn, hãy chạy lệnh sau để cài đặt plugin:

    flutter pub add cloud_functions
    
  3. Sau khi hoàn tất, hãy xây dựng lại ứng dụng Flutter của bạn:

    flutter run
    
  4. Sau khi cài đặt, bạn có thể truy cập plugin cloud_functions bằng cách nhập nó vào mã Dart của mình:

    import 'package:cloud_functions/cloud_functions.dart';
    

C++

Đối với C++ với Android :

  1. Làm theo hướng dẫn để thêm Firebase vào dự án C++ của bạn .
  2. Thêm thư viện firebase_functions vào tệp CMakeLists.txt của bạn.

Đối với C++ với nền tảng Apple :

  1. Làm theo hướng dẫn để thêm Firebase vào dự án C++ của bạn .
  2. Thêm nhóm Chức năng đám mây vào Podfile của bạn:
    pod 'Firebase/Functions'
  3. Lưu tệp rồi chạy:
    pod install
  4. Thêm lõi Firebase và khung Chức năng đám mây từ SDK Firebase C++ vào dự án Xcode của bạn.
    • firebase.framework
    • firebase_functions.framework

Đoàn kết

  1. Làm theo hướng dẫn để thêm Firebase vào dự án Unity của bạn .
  2. Thêm FirebaseFunctions.unitypackage từ SDK Unity Firebase vào dự án Unity của bạn.

Khởi tạo SDK khách

Khởi tạo một phiên bản của Chức năng đám mây:

Nhanh

lazy var functions = Functions.functions()

Mục tiêu-C

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

API không gian tên 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 mô-đun 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);

Đoàn kết

functions = Firebase.Functions.DefaultInstance;

Gọi hàm

Nhanh

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

Mục tiêu-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 không gian tên web

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

API mô-đun 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);
}

Đoàn kết

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 client

Máy khách nhận được lỗi nếu máy chủ đưa ra lỗi hoặc nếu lời hứa kết quả bị từ chối.

Nếu lỗi mà hàm trả về thuộc loại function.https.HttpsError thì máy khách sẽ nhận được code lỗi, messagedetails từ lỗi máy chủ. Nếu không, lỗi 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 được của bạn.

Nhanh

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]
  }
  // ...
}

Mục tiêu-C

if (error) {
  if ([error.domain isEqual:@"com.firebase.functions"]) {
    FIRFunctionsErrorCode code = error.code;
    NSString *message = error.localizedDescription;
    NSObject *details = error.userInfo[@"details"];
  }
  // ...
}

API không gian tên 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 mô-đun 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);
  // ...

Đoàn kết

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

Trước khi khởi chạy ứng dụng, bạn nên bật Kiểm tra ứng dụng để giúp đảm bảo rằng chỉ ứng dụng của bạn mới có thể truy cập vào điểm cuối của chức năng có thể gọi được.