تتيح لك حِزم تطوير البرامج (SDK) للعميل في Cloud Functions for Firebase استدعاء الدوال مباشرةً من تطبيق Firebase. لاستدعاء دالة من تطبيقك بهذه الطريقة، عليك كتابة دالة HTTP قابلة للاستدعاء ونشرها في Cloud Functions، و ثم إضافة منطق العميل لاستدعاء الدالة من تطبيقك.
من المهمّ أن تتذكّر أنّ الدوال القابلة للاستدعاء عبر HTTP مشابهة لدوال HTTP ولكنها ليست متطابقة معها. لاستخدام الدوال القابلة للاستدعاء عبر HTTP، عليك استخدام حزمة تطوير البرامج (SDK) للعميل الخاصة بمنصّتك مع واجهة برمجة التطبيقات للواجهة الخلفية (أو تنفيذ البروتوكول). تختلف الدوال القابلة للاستدعاء عن دوال HTTP في ما يلي:
- في الدوال القابلة للاستدعاء، يتم تلقائيًا تضمين Firebase Authentication وFCM وApp Check في الطلبات، إذا كانت متوفّرة.
- يزيل المشغِّل تلقائيًا تسلسل نص طلب البيانات ويتحقّق من صحة رموز المصادقة.
تتفاعل حزمة Firebase لـ Cloud Functions من الجيل الثاني والإصدارات الأحدث مع الحد الأدنى من إصدارات حِزم تطوير البرامج (SDK) لعميل Firebase التالية من أجل دعم الدوال القابلة للاستدعاء عبر HTTPS:
- Firebase SDK لمنصّات Apple 12.13.0
- Firebase SDK لنظام التشغيل Android 22.1.1
- حزمة Firebase Modular Web SDK الإصدار 9.7.0
إذا أردت إضافة وظائف مشابهة إلى تطبيق تم إنشاؤه على منصّة غير متوافقة
، اطّلِع على مواصفات البروتوكول لـ https.onCall. تقدّم بقية هذا الدليل تعليمات حول كيفية كتابة دالة قابلة للاستدعاء عبر HTTP ونشرها واستدعائها لمنصّات Apple وAndroid والويب وC++ وUnity.
كتابة الدالة القابلة للاستدعاء ونشرها
تستند نماذج الرموز البرمجية في هذا القسم إلى نموذج بداية سريعة كامل يوضّح كيفية إرسال الطلبات إلى دالة من جهة الخادم والحصول على ردّ باستخدام إحدى حِزم تطوير البرامج (SDK) للعميل. للبدء، استورِد الوحدات المطلوبة:
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 (تجريبية)
// Dependencies for callable functions.
import 'package:firebase_functions/firebase_functions.dart';
استخدِم معالج الطلبات لمنصّتك لإنشاء دالة قابلة للاستدعاء عبر 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."""
Dart (تجريبية)
// Adds two numbers to each other.
firebase.https.onCall(name: 'addNumbers', (request, response) async {
تحتوي المَعلمة request على البيانات التي تم تمريرها من تطبيق العميل بالإضافة إلى سياق إضافي، مثل حالة المصادقة. بالنسبة إلى دالة قابلة للاستدعاء تحفظ رسالة نصية في Realtime Database,
على سبيل المثال، 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", "")
Dart (تجريبية)
// 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',
);
يمكن أن تؤدي المسافة بين موقع الدالة القابلة للاستدعاء وموقع العميل الذي يستدعيها إلى حدوث وقت استجابة للشبكة. لتحسين الأداء، ننصحك بتحديد موقع الدالة حيثما ينطبق ذلك، والتأكّد من مطابقة موقع الدالة القابلة للاستدعاء مع الموقع الذي تم ضبطه عند إعداد حزمة تطوير البرامج (SDK) على جانب العميل.
يمكنك اختياريًا إرفاق شهادة إثبات من App Check للمساعدة في حماية موارد الواجهة الخلفية من إساءة الاستخدام، مثل الاحتيال في الفوترة أو التصيّد الاحتيالي. اطّلِع على مقالة تفعيل فرض استخدام App Check لـ Cloud Functions.
إرسال النتيجة
لإرسال البيانات إلى العميل، عليك عرض بيانات يمكن ترميزها بتنسيق 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,
}
Dart (تجريبية)
// returning result.
return CallableResult({
'firstNumber': firstNumber,
'secondNumber': secondNumber,
'operator': '+',
'operationResult': firstNumber + secondNumber,
});
يتم عرض النص الذي تم تنظيفه من مثال نص الرسالة لكلّ من العميل وإلى Realtime Database. في 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}
يجب أن تعرض دالتك قيمة أو، في حالة Node.js، وعدًا يتم تنفيذه بقيمة. بخلاف ذلك، قد تنتهي الدالة قبل إرسال البيانات إلى العميل. يُرجى الاطّلاع على مقالة إنهاء الدوال للحصول على إرشادات.
إرسال نتائج البث وتلقّيها
تتضمّن الدوال القابلة للاستدعاء آليات للتعامل مع نتائج البث. إذا كان لديك حالة استخدام تتطلّب البث، يمكنك ضبط البث في الطلب القابل للاستدعاء، ثم استخدام الطريقة المناسبة من حزمة تطوير البرامج (SDK) للعميل لاستدعاء الدالة.
إرسال نتائج البث
لبث النتائج التي يتم إنشاؤها بمرور الوقت بكفاءة، مثل النتائج الواردة من عدد من طلبات واجهة برمجة التطبيقات المنفصلة أو واجهة برمجة تطبيقات الذكاء الاصطناعي التوليدي، تحقَّق من السمة acceptsStreaming في طلبك القابل للاستدعاء. عند ضبط هذه السمة على true، يمكنك بث النتائج إلى العميل باستخدام response.sendChunk().
على سبيل المثال، إذا كان أحد التطبيقات بحاجة إلى استرجاع بيانات التنبؤات الجوية لمواقع جغرافية متعدّدة، يمكن للدالة القابلة للاستدعاء إرسال التنبؤات الجوية لكل موقع جغرافي على حدة إلى العملاء الذين طلبوا ردًا على البث، بدلاً من جعلهم ينتظرون إلى أن يتم تنفيذ جميع طلبات التنبؤات الجوية:
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); });
يُرجى العِلم أنّ طريقة عمل response.sendChunk() تعتمد على تفاصيل معيّنة في طلب العميل:
إذا طلب العميل ردًا على البث: ترسل الدالة
response.sendChunk(data)جزء البيانات على الفور.إذا لم يطلب العميل ردًا على البث: لا تنفّذ الدالة
response.sendChunk()أي إجراء في هذا الاستدعاء. يتم إرسال الردّ الكامل بعد أن تصبح جميع البيانات جاهزة.
لتحديد ما إذا كان العميل يطلب ردًا على البث، تحقَّق من السمة request.acceptsStreaming. على سبيل المثال، إذا كانت request.acceptsStreaming غير صحيحة، يمكنك اختيار تخطّي أي عمل كثيف الاستخدام للموارد مرتبط تحديدًا بإعداد أو إرسال أجزاء فردية، لأنّ العميل لا يتوقّع تسليمًا تدريجيًا.
تلقّي نتائج البث
في سيناريو نموذجي، يطلب العميل البث باستخدام الطريقة .stream ثم يتكرّر خلال النتائج:
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);
تكرار خلال التكرار غير المتزامن stream كما هو موضّح يشير انتظار الوعد data إلى العميل بأنّ الطلب قد اكتمل
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)
}
}
}
لاستخدام دالة الإضافة asFlow()، أضِف مكتبة org.jetbrains.kotlinx:kotlinx-coroutines-reactive كاعتمادية إلى ملف build.gradle(.kts) الخاص بالتطبيق.
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() {
}
});
ضبط مشاركة المراجع مع نطاقات خارجية (CORS)
استخدِم الخيار cors للتحكّم في المصادر التي يمكنها الوصول إلى دالتك.
بشكل تلقائي، يتم ضبط الدوال القابلة للاستدعاء عبر HTTP للسماح بالطلبات من جميع المصادر. للسماح ببعض الطلبات المتعدّدة المصادر، وليس كلها، عليك تمرير قائمة بنطاقات أو تعبيرات عادية محدّدة يجب السماح بها. على سبيل المثال:
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 (تجريبية)
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!');
},
);
});
}
لمنع الطلبات المتعدّدة المصادر، اضبط سياسة cors على false.
التعامل مع الأخطاء
لضمان حصول العميل على تفاصيل مفيدة عن الخطأ، عليك عرض الأخطاء من دالة قابلة للاستدعاء من خلال طرح (أو في Node.js عرض وعد تم رفضه باستخدام) مثيل من functions.https.HttpsError أو https_fn.HttpsError.
يحتوي الخطأ على سمة 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.",
)
Dart (تجريبية)
// 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.',
);
}
نشر الدالة القابلة للاستدعاء
بعد حفظ دالة قابلة للاستدعاء مكتملة ضمن index.js، يتم نشرها مع جميع الدوال الأخرى عند تشغيل firebase deploy.
لنشر الدالة القابلة للاستدعاء فقط، استخدِم الوسيطة --only كما هو موضّح لتنفيذ
عمليات نشر جزئية:
firebase deploy --only functions:addMessage
إذا واجهت أخطاء في الأذونات عند نشر الدوال، تأكَّد من أنّ أدوار "إدارة الهوية وإمكانية الوصول" المناسبة تم منحها للمستخدم الذي يشغّل أوامر النشر.
إعداد بيئة تطوير العميل
تأكَّد من استيفاء أي متطلبات أساسية، ثم أضِف التبعيات المطلوبة ومكتبات العميل إلى تطبيقك.
iOS+
اتّبِع التعليمات لـ إضافة Firebase إلى تطبيق Apple.
استخدِم Swift Package Manager لتثبيت تبعيات Firebase وإدارتها.
- في Xcode، افتح مشروع تطبيقك وانتقِل إلى ملف > إضافة حِزم.
- عندما يُطلب منك ذلك، أضِف مستودع حزمة Firebase Apple platforms SDK:
- اختَر مكتبة Cloud Functions.
- أضِف العلامة
-ObjCإلى قسم علامات الرابط الأخرى في إعدادات الإصدار للهدف. - عند الانتهاء، سيبدأ Xcode تلقائيًا في حلّ تبعياتك وتنزيلها في الخلفية.
https://github.com/firebase/firebase-ios-sdk.git
Web
- اتّبِع التعليمات لإضافة Firebase إلى تطبيق الويب. تأكَّد من تشغيل الأمر التالي من الوحدة الطرفية:
npm install firebase@12.12.1 --save
اطلب يدويًا كلاً من 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);
Android
في ملف 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:34.12.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") }
باستخدام 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:22.1.1") }
إعداد حزمة تطوير البرامج (SDK) للعميل
يمكنك إعداد مثيل من 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();
استدعاء الدالة
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;
}
});
ننصح بما يلي: منع إساءة الاستخدام باستخدام App Check
قبل إطلاق تطبيقك، عليك تفعيل App Check للمساعدة في ضمان إمكانية وصول تطبيقاتك فقط إلى نقاط نهاية الدوال القابلة للاستدعاء.