وظائف المكالمات من تطبيقك


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

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

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

يمكن تشغيل الجيل الثاني والجيل الأعلى من حزمة تطوير البرامج (SDK) لمنصّة Firebase for Cloud Functions مع الإصدار الأدنى من إصدارات حزمة تطوير البرامج (SDK) لبرامج Firebase هذه لكي تتوافق مع وظائف HTTPS القابلة للاستدعاء:

  • حزمة تطوير البرامج (SDK) لمنصّة Firebase للإصدار 10.28.0 من أنظمة Apple الأساسية
  • حزمة تطوير البرامج (SDK) لمنصّة Firebase للإصدار 21.0.0 من نظام التشغيل Android
  • Firebase Modular Web SDK - الإصدار 9.7.0

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

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

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

Node.js

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

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

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

استخدِم معالِج الطلبات للنظام الأساسي (functions.https.onCall) أو on_call) لإنشاء دالة قابلة للاستدعاء من خلال HTTPS. تستخدم هذه الطريقة معلمة الطلب وهي:

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

تحتوي المَعلمة request على بيانات يتم ضبطها من تطبيق العميل، بالإضافة إلى سياق إضافي، مثل حالة المصادقة. بالنسبة إلى الدالة القابلة للاستدعاء التي تحفظ رسالة نصية في قاعدة بيانات الوقت الفعلي، على سبيل المثال، قد تحتوي data على نص الرسالة، بالإضافة إلى معلومات المصادقة في 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", "")

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

يمكنك اختياريًا إرفاق مصادقة "فحص التطبيق" للمساعدة في حماية موارد الخلفية من إساءة الاستخدام، مثل الفوترة الاحتيالية أو التصيّد الاحتيالي. اطّلِع على تفعيل فرض "التحقّق من التطبيقات" لوظائف السحابة الإلكترونية.

إعادة إرسال النتيجة

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

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
}

يتم إرجاع النص الذي تم تنظيفه من مثال نص الرسالة إلى كل من العميل وقاعدة بيانات الوقت الفعلي. في Node.js، يمكن تنفيذ ذلك بشكل غير متزامن باستخدام وعد 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}

إعداد سياسة مشاركة الموارد المتعددة المصادر (CORS)

استخدِم الخيار cors لتحديد المصادر التي يمكنها الوصول إلى الدالة.

يتم تلقائيًا ضبط سياسة مشاركة الموارد المتعددة المصادر (CORS) في الدوال القابلة للاستدعاء للسماح بالطلبات من جميع المصادر. للسماح ببعض الطلبات الواردة من عدّة مصادر، ولكن ليس كلها، عليك تمرير قائمة بالنطاقات أو التعبيرات العادية المحدّدة التي ينبغي السماح بها. على سبيل المثال:

Node.js

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

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

لحظر الطلبات من مصادر متعددة، عليك ضبط سياسة cors على false.

التعامل مع الأخطاء

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

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

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

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

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

firebase deploy --only functions:addMessage

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

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

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

iOS+

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

يمكنك استخدام "مدير حزم Swift" لتثبيت اعتماديات Firebase وإدارتها.

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

Web

  1. اتّبِع التعليمات لإضافة Firebase إلى تطبيق الويب، واحرص على تشغيل الأمر التالي من الوحدة الطرفية:
    npm install firebase@10.12.2 --save
    
  2. تتطلّب يدويًا كلاً من وظائف Firebase الأساسية ووظائف السحابة الإلكترونية:

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

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

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

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

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

    إذا اخترت عدم استخدام قائمة العناصر في Firebase، يجب تحديد كل إصدار من مكتبة 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:21.0.0")
    }
    
    هل تبحث عن وحدة مكتبة خاصة بلغة Kotlin؟ اعتبارًا من تشرين الأول (أكتوبر) 2023 (الإصدار 32.5.0 من Firebase)، أصبح بإمكان مطوّري لغة Kotlin وJava الاعتماد على وحدة المكتبة الرئيسية (لمعرفة التفاصيل، يُرجى الاطّلاع على الأسئلة الشائعة حول هذه المبادرة).

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

إعداد مثيل من دوال السحابة:

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+KTX

private lateinit var functions: FirebaseFunctions
// ...
functions = Firebase.functions

Java

private FirebaseFunctions mFunctions;
// ...
mFunctions = FirebaseFunctions.getInstance();

استدعِ الدالة.

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

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

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

قبل إطلاق تطبيقك، عليك تفعيل ميزة فحص التطبيقات للمساعدة في ضمان وصول تطبيقاتك فقط إلى نقاط نهاية الوظائف القابلة للاستدعاء.