استدعاء الدوال من تطبيقك (الجيل الأول)

تتيح لك حزم تطوير البرامج (SDK) لعملاء Cloud Functions for Firebase استدعاء الدوال مباشرةً من تطبيق Firebase. لاستدعاء دالة من تطبيقك بهذه الطريقة، اكتب دالة HTTP قابلة للاستدعاء في Cloud Functions وانشرها، ثم أضِف منطق العميل لاستدعاء الدالة من تطبيقك.

من المهمّ أن تضع في اعتبارك أنّ الدوالّ القابلة للاستدعاء عبر HTTP مشابهة لدوالّ HTTP ولكنّها ليست مطابقة لها. لاستخدام الدوال القابلة للاستدعاء عبر HTTP، يجب استخدام حزمة تطوير البرامج (SDK) للعميل على نظامك الأساسي مع واجهة برمجة التطبيقات الخلفية (أو تنفيذ البروتوكول). تختلف الدوال القابلة للاستدعاء عن دوال HTTP في ما يلي:

  • باستخدام الدوال القابلة للاستدعاء، يتم تلقائيًا تضمين رموز Firebase Authentication المميّزة ورموز FCM المميّزة ورموز App Check المميّزة في الطلبات، عندما تكون متاحة.
  • يعمل المشغّل تلقائيًا على إلغاء تسلسل نص الطلب والتحقّق من صحة رموز المصادقة المميّزة.

تتوافق حزمة تطوير البرامج (SDK) لـ Firebase في الإصدار الثاني من Cloud Functions والإصدارات الأحدث مع الحد الأدنى من إصدارات حزمة تطوير البرامج (SDK) لعميل Firebase التالية لإتاحة دوال HTTPS القابلة للاستدعاء:

  • الإصدار 13.1.0 من حزمة تطوير البرامج (SDK) لـ "Firebase" على منصات "Apple"
  • الإصدار 23.0.0 من حزمة SDK لـ "Firebase" على "Android"
  • الإصدار 9.7.0 من حزمة تطوير البرامج (SDK) المعيارية للويب من Firebase

إذا أردت إضافة وظائف مشابهة إلى تطبيق تم إنشاؤه على نظام أساسي غير متوافق، يُرجى الاطّلاع على مواصفات بروتوكول https.onCall. يقدّم الجزء المتبقي من هذا الدليل تعليمات حول كيفية كتابة دالة HTTP قابلة للاستدعاء ونشرها واستدعائها لمنصات Apple وAndroid والويب وC++‎ وUnity.

كتابة الدالة القابلة للاستدعاء ونشرها

استخدِم functions.https.onCall لإنشاء دالة قابلة للاستدعاء عبر HTTPS. تتطلّب هذه الطريقة مَعلمتَين: data، وcontext الاختيارية:

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

بالنسبة إلى دالة قابلة للاستدعاء تحفظ رسالة نصية في Realtime Database، على سبيل المثال، يمكن أن يحتوي data على نص الرسالة، بينما تمثّل مَعلمات context معلومات مصادقة المستخدم:

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

يمكن أن تؤدي المسافة بين موقع الدالة القابلة للاستدعاء وموقع العميل المستدعي إلى حدوث وقت استجابة في الشبكة. لتحسين الأداء، ننصحك بتحديد الموقع الجغرافي للدالة حيثما أمكن، والتأكّد من توافق الموقع الجغرافي للدالة القابلة للاستدعاء مع الموقع الجغرافي الذي تم ضبطه عند إعداد حزمة تطوير البرامج (SDK) على جهة العميل.

يمكنك اختياريًا إرفاق شهادة App Check للمساعدة في حماية موارد الخلفية من إساءة الاستخدام، مثل الاحتيال عبر الفوترة أو التصيّد الاحتيالي. يُرجى الاطّلاع على تفعيل تنفيذ App Check في Cloud Functions.

إرسال النتيجة مرة أخرى

لإرسال البيانات مرة أخرى إلى العميل، يجب عرض بيانات يمكن ترميزها بتنسيق JSON. على سبيل المثال، لإرجاع نتيجة عملية جمع:

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

لإرجاع البيانات بعد عملية غير متزامنة، يجب إرجاع وعد. يتم إرسال البيانات التي يعرضها الوعد إلى العميل. على سبيل المثال، يمكنك عرض نص تم تنقيته كتبته الدالة القابلة للاستدعاء في 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};
})

معالجة الأخطاء

لضمان حصول العميل على تفاصيل مفيدة عن الخطأ، يمكنك عرض الأخطاء من دالة قابلة للاستدعاء من خلال طرح (أو عرض وعد مرفوض باستخدام) مثيل من functions.https.HttpsError. يحتوي الخطأ على سمة code يمكن أن تكون إحدى القيم المدرَجة في functions.https.HttpsError. تحتوي الأخطاء أيضًا على سلسلة message، والتي يتم ضبطها تلقائيًا على سلسلة فارغة. ويمكن أن تحتوي أيضًا على حقل details اختياري بقيمة عشوائية. إذا ظهر خطأ غير HttpsError من الدوال، سيتلقّى العميل بدلاً من ذلك خطأً مع الرسالة INTERNAL والرمز internal.

على سبيل المثال، يمكن أن تعرض الدالة أخطاء في التحقّق من صحة البيانات والمصادقة مع رسائل خطأ لإعادتها إلى العميل الذي يطلبها:

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

نشر الدالة القابلة للاستدعاء

بعد حفظ دالة قابلة للاستدعاء مكتملة ضمن index.js، يتم نشرها مع جميع الدوال الأخرى عند تشغيل firebase deploy. لنشر الدالة القابلة للاستدعاء فقط، استخدِم الوسيطة --only كما هو موضّح لإجراء عمليات نشر جزئية:

firebase deploy --only functions:addMessage

إذا واجهت أخطاء في الأذونات عند نشر الدوال، تأكَّد من أنّه تم منح أدوار إدارة الهوية وإمكانية الوصول المناسبة للمستخدم الذي يشغّل أوامر النشر.

إعداد بيئة تطوير برامج العميل

تأكَّد من استيفاء أي متطلبات أساسية، ثم أضِف التبعيات المطلوبة ومكتبات العملاء إلى تطبيقك.

iOS+‎

اتّبِع التعليمات لإضافة Firebase إلى تطبيق Apple.

استخدِم أداة Swift Package Manager لتثبيت تبعيات Firebase وإدارتها.

  1. في Xcode، افتح مشروع تطبيقك، ثم انتقِل إلى ملف > إضافة حِزم (File > Add Packages).
  2. عندما يُطلب منك ذلك، أضِف مستودع حزمة تطوير البرامج (SDK) لمنصات Apple في Firebase:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. اختَر مكتبة "Cloud Functions".
  5. أضِف العلامة -ObjC إلى قسم علامات الربط الأخرى (Other Linker Flags) في إعدادات الإنشاء الخاصة بالهدف.
  6. بعد الانتهاء، سيبدأ Xcode تلقائيًا في حلّ التبعيات وتنزيلها في الخلفية.

Web

  1. اتّبِع التعليمات من أجل إضافة Firebase إلى تطبيق الويب. تأكَّد من تشغيل الأمر التالي من الوحدة الطرفية:
    npm install firebase@13.1.0 --save
  2. اطلب يدويًا كلاً من Firebase core و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. اتّبِع التعليمات لإضافة Firebase إلى تطبيق الويب.
  2. أضِف مكتبات Firebase الأساسية ومكتبات برامج 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>

تتوفّر حزمة تطوير البرامج (SDK) لـ Cloud Functions أيضًا كحزمة npm.

  1. نفِّذ الأمر التالي من الوحدة الطرفية:
    npm install firebase@8.10.1 --save
  2. اطلب يدويًا كلاً من Firebase core وCloud Functions:
    const firebase = require("firebase");
    // Required for side-effects
    require("firebase/functions");

Kotlin

  1. اتّبِع التعليمات من أجل إضافة Firebase إلى تطبيق Android.

  2. في ملف Gradle للوحدة (على مستوى التطبيق) (عادةً <project>/<app-module>/build.gradle.kts أو <project>/<app-module>/build.gradle)، أضِف الاعتمادية لمكتبة Cloud Functions على Android. ننصح باستخدام Firebase Android BoM للتحكّم في إصدارات المكتبة.

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

    باستخدام Firebase Android BoM، سيستخدم تطبيقك دائمًا إصدارات متوافقة من مكتبات Firebase لنظام التشغيل Android.

    (بديل)  إضافة تبعيات مكتبة Firebase بدون استخدام BoM

    إذا اخترت عدم استخدام Firebase BoM، عليك تحديد كل إصدار من مكتبة Firebase في سطر التبعية الخاص به.

    يُرجى العِلم أنّه في حال استخدام مكتبات Firebase متعددة في تطبيقك، ننصحك بشدة باستخدام BoM لإدارة إصدارات المكتبات، ما يضمن توافق جميع الإصدارات.

    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. اتّبِع التعليمات من أجل إضافة Firebase إلى تطبيق Android.

  2. في ملف Gradle للوحدة (على مستوى التطبيق) (عادةً <project>/<app-module>/build.gradle.kts أو <project>/<app-module>/build.gradle)، أضِف الاعتمادية لمكتبة Cloud Functions على Android. ننصح باستخدام Firebase Android BoM للتحكّم في إصدارات المكتبة.

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

    باستخدام Firebase Android BoM، سيستخدم تطبيقك دائمًا إصدارات متوافقة من مكتبات Firebase لنظام التشغيل Android.

    (بديل)  إضافة تبعيات مكتبة Firebase بدون استخدام BoM

    إذا اخترت عدم استخدام Firebase BoM، عليك تحديد كل إصدار من مكتبة Firebase في سطر التبعية الخاص به.

    يُرجى العِلم أنّه في حال استخدام مكتبات Firebase متعددة في تطبيقك، ننصحك بشدة باستخدام BoM لإدارة إصدارات المكتبات، ما يضمن توافق جميع الإصدارات.

    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. اتّبِع التعليمات لإضافة Firebase إلى تطبيق Flutter.

  2. من جذر مشروع Flutter، نفِّذ الأمر التالي لتثبيت المكوّن الإضافي:

    flutter pub add cloud_functions
    
  3. بعد الانتهاء، أعِد إنشاء تطبيق Flutter:

    flutter run
    
  4. بعد تثبيت المكوّن الإضافي cloud_functions، يمكنك الوصول إليه من خلال استيراده في رمز Dart البرمجي:

    import 'package:cloud_functions/cloud_functions.dart';
    

C++‎

بالنسبة إلى C++‎ مع Android:

  1. اتّبِع التعليمات لإضافة Firebase إلى مشروع C++‎.
  2. أضِف مكتبة firebase_functions إلى ملف CMakeLists.txt.

بالنسبة إلى C++‎ مع أنظمة Apple الأساسية:

  1. اتّبِع التعليمات لإضافة Firebase إلى مشروع C++‎.
  2. أضِف مجموعة الإعلانات المتسلسلة Cloud Functions إلى Podfile:
    pod 'Firebase/Functions'
  3. احفظ الملف، ثم شغِّل:
    pod install
  4. أضِف إطارَي عمل Firebase الأساسي وCloud Functions من حزمة تطوير البرامج (SDK) لـ Firebase C++ إلى مشروع Xcode.
    • firebase.framework
    • firebase_functions.framework

Unity

  1. اتّبِع التعليمات لإضافة Firebase إلى مشروع Unity.
  2. أضِف FirebaseFunctions.unitypackage من حزمة تطوير البرامج (SDK) لـ Firebase Unity إلى مشروعك على Unity.

إعداد حزمة تطوير البرامج (SDK) للعميل

إعداد مثيل من 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;

استدعاء الدالة

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

معالجة الأخطاء في البرنامج

يتلقّى العميل خطأ إذا عرض الخادم خطأ أو إذا تم رفض الوعد الناتج.

إذا كان الخطأ الذي تعرضه الدالة من النوع function.https.HttpsError، سيتلقّى العميل الخطأ code وmessage وdetails من خطأ الخادم. بخلاف ذلك، يحتوي الخطأ على الرسالة INTERNAL والرمز INTERNAL. يمكنك الاطّلاع على إرشادات حول كيفية معالجة الأخطاء في الدالة القابلة للاستدعاء.

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

ضبط مهلة العميل

تستخدم حِزم تطوير البرامج (SDK) لبرنامج Cloud Functions تلقائيًا مهلة تبلغ 70 ثانية للطلبات القابلة للاستدعاء. إذا استغرقت دالة قابلة للاستدعاء أكثر من 70 ثانية لإكمالها، تنهي حزمة تطوير البرامج (SDK) للعميل الطلب بخطأ DEADLINE_EXCEEDED (deadline-exceeded)، حتى إذا تم ضبط مهلة أطول من جهة الخادم.

لإتاحة الدوال القابلة للاستدعاء التي تستغرق وقتًا طويلاً، يجب زيادة المهلة على كل من الخادم والعميل:

  1. زيادة مهلة الدالة من جهة الخادم (راجِع ضبط المهلة وتخصيص الذاكرة).
  2. يمكنك زيادة مهلة جهة العميل عند ضبط المرجع القابل للاستدعاء في تطبيقك:

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

إجراء مقترَح: منع إساءة الاستخدام من خلال App Check

قبل إطلاق تطبيقك، عليك تفعيل App Check لضمان أنّه لا يمكن إلا لتطبيقاتك الوصول إلى نقاط نهاية الدوال القابلة للاستدعاء.