Cloud Functions for Firebase ক্লায়েন্ট SDK-গুলো আপনাকে সরাসরি একটি Firebase অ্যাপ থেকে ফাংশন কল করার সুযোগ দেয়। আপনার অ্যাপ থেকে এইভাবে একটি ফাংশন কল করতে, Cloud Functions এ একটি HTTP Callable ফাংশন লিখুন এবং ডিপ্লয় করুন, এবং তারপর আপনার অ্যাপ থেকে ফাংশনটি কল করার জন্য ক্লায়েন্ট লজিক যোগ করুন।
এটা মনে রাখা গুরুত্বপূর্ণ যে HTTP কলযোগ্য ফাংশনগুলো HTTP ফাংশনের অনুরূপ হলেও হুবহু এক নয় । HTTP কলযোগ্য ফাংশন ব্যবহার করার জন্য আপনাকে অবশ্যই আপনার প্ল্যাটফর্মের ক্লায়েন্ট SDK-এর সাথে ব্যাকএন্ড API ব্যবহার করতে হবে (অথবা প্রোটোকলটি ইমপ্লিমেন্ট করতে হবে)। HTTP ফাংশনের সাথে কলযোগ্য ফাংশনগুলোর এই মূল পার্থক্যগুলো রয়েছে:
- কলযোগ্য ফাংশনের ক্ষেত্রে, Firebase Authentication টোকেন, FCM টোকেন এবং App Check টোকেন, উপলব্ধ থাকলে, স্বয়ংক্রিয়ভাবে অনুরোধগুলিতে অন্তর্ভুক্ত হয়ে যায়।
- ট্রিগারটি স্বয়ংক্রিয়ভাবে রিকোয়েস্ট বডিকে ডিসিরিয়ালাইজ করে এবং অথ টোকেনগুলো যাচাই করে।
HTTPS কলযোগ্য ফাংশন সমর্থন করার জন্য, Firebase SDK for Cloud Functions 2nd gen এবং তার উচ্চতর সংস্করণগুলো Firebase ক্লায়েন্ট SDK-এর এই ন্যূনতম সংস্করণগুলোর সাথে আন্তঃকার্যকরী হয়:
- Apple প্ল্যাটফর্মের জন্য Firebase এসডিকে ১২.১১.০
- Android জন্য Firebase এসডিকে ২২.১.০
- ফায়ারবেস মডিউলার ওয়েব এসডিকে সংস্করণ ৯.৭.০
যদি আপনি কোনো অসমর্থিত প্ল্যাটফর্মে তৈরি অ্যাপে অনুরূপ কার্যকারিতা যোগ করতে চান, তাহলে https.onCall এর প্রোটোকল স্পেসিফিকেশন দেখুন। এই গাইডের বাকি অংশে অ্যাপল প্ল্যাটফর্ম, অ্যান্ড্রয়েড, ওয়েব, C++ এবং ইউনিটির জন্য কীভাবে একটি HTTP কলযোগ্য ফাংশন লিখতে, স্থাপন করতে এবং কল করতে হয়, তার নির্দেশাবলী দেওয়া হয়েছে।
কলযোগ্য ফাংশনটি লিখুন এবং স্থাপন করুন
এই বিভাগের কোড উদাহরণগুলো একটি সম্পূর্ণ কুইকস্টার্ট স্যাম্পলের উপর ভিত্তি করে তৈরি, যা দেখায় কিভাবে ক্লায়েন্ট SDK-গুলোর একটি ব্যবহার করে সার্ভার-সাইড ফাংশনে রিকোয়েস্ট পাঠানো যায় এবং রেসপন্স পাওয়া যায়। শুরু করার জন্য, প্রয়োজনীয় মডিউলগুলো ইম্পোর্ট করুন:
নোড.জেএস
// 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");
পাইথন
# Dependencies for callable functions.
from firebase_functions import https_fn, options
# Dependencies for writing to Realtime Database.
from firebase_admin import db, initialize_app
একটি HTTPS কলযোগ্য ফাংশন তৈরি করতে আপনার প্ল্যাটফর্মের জন্য রিকোয়েস্ট হ্যান্ডলার ( functions.https.onCall বা on_call ) ব্যবহার করুন। এই মেথডটি একটি রিকোয়েস্ট প্যারামিটার গ্রহণ করে:
নোড.জেএস
// Saves a message to the Firebase Realtime Database but sanitizes the
// text by removing swearwords.
exports.addmessage = onCall((request) => {
// ...
});
পাইথন
@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 প্যারামিটারে ক্লায়েন্ট অ্যাপ থেকে পাঠানো ডেটার পাশাপাশি অথেনটিকেশন স্টেটের মতো অতিরিক্ত প্রাসঙ্গিক তথ্যও থাকে। উদাহরণস্বরূপ, Realtime Database একটি টেক্সট মেসেজ সেভ করে এমন একটি কলযোগ্য ফাংশনের ক্ষেত্রে, data মেসেজের টেক্সটের সাথে auth এর মধ্যে অথেনটিকেশন তথ্যও থাকতে পারে।
নোড.জেএস
// 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;
পাইথন
# 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 ইনিশিয়ালাইজ করার সময় সেট করা অবস্থানের সাথে কলযোগ্য ফাংশনের অবস্থানটি যেন মিলে যায়, তা নিশ্চিত করুন।
ঐচ্ছিকভাবে, আপনি আপনার ব্যাকএন্ড রিসোর্সগুলিকে বিলিং জালিয়াতি বা ফিশিংয়ের মতো অপব্যবহার থেকে রক্ষা করতে একটি App Check অ্যাটেস্টেশন সংযুক্ত করতে পারেন। Cloud Functions জন্য App Check এনফোর্সমেন্ট সক্ষম করুন দেখুন।
ফলাফল ফেরত পাঠান
ক্লায়েন্টের কাছে ডেটা ফেরত পাঠাতে, এমন ডেটা ফেরত দিন যা JSON এনকোড করা যায়। উদাহরণস্বরূপ, একটি যোগ অপারেশনের ফলাফল ফেরত দিতে:
নোড.জেএস
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: "+",
operationResult: firstNumber + secondNumber,
};
পাইথন
return {
"firstNumber": first_number,
"secondNumber": second_number,
"operator": "+",
"operationResult": first_number + second_number
}
মেসেজ টেক্সট উদাহরণ থেকে পরিমার্জিত টেক্সট ক্লায়েন্ট এবং Realtime Database উভয়কেই ফেরত পাঠানো হয়। 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};
})
পাইথন
# 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-এর ক্ষেত্রে, একটি Promise রিটার্ন করতে হবে যা একটি ভ্যালু দিয়ে রিজলভ হয়। অন্যথায়, ক্লায়েন্টের কাছে ডেটা ফেরত পাঠানোর আগেই ফাংশনটি টার্মিনেট হয়ে যেতে পারে। নির্দেশনার জন্য ‘Terminate functions’ দেখুন।
স্ট্রিমিং ফলাফল প্রেরণ এবং গ্রহণ করুন
কলযোগ্য ফাংশনগুলিতে স্ট্রিমিং ফলাফল পরিচালনা করার ব্যবস্থা রয়েছে। যদি আপনার এমন কোনো ব্যবহারের ক্ষেত্র থাকে যেখানে স্ট্রিমিং প্রয়োজন, তবে আপনি কলযোগ্য অনুরোধে স্ট্রিমিং কনফিগার করতে পারেন এবং তারপর ফাংশনটি কল করার জন্য ক্লায়েন্ট SDK থেকে উপযুক্ত পদ্ধতিটি ব্যবহার করতে পারেন।
স্ট্রিমিং ফলাফল পাঠান
সময়ের সাথে সাথে তৈরি হওয়া ফলাফল, যেমন একাধিক পৃথক API অনুরোধ বা একটি জেনারেটিভ AI API থেকে প্রাপ্ত ফলাফল, দক্ষতার সাথে স্ট্রিম করতে আপনার কলযোগ্য অনুরোধে 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 মান false হয়, তাহলে আপনি আলাদা আলাদা চাঙ্ক প্রস্তুত করা বা পাঠানোর মতো রিসোর্স-ইনটেনসিভ কাজগুলো এড়িয়ে যাওয়ার সিদ্ধান্ত নিতে পারেন, কারণ ক্লায়েন্ট কোনো ইনক্রিমেন্টাল ডেলিভারি আশা করছে না।
স্ট্রিমিং ফলাফল গ্রহণ করুন
সাধারণত, ক্লায়েন্ট .stream মেথড ব্যবহার করে স্ট্রিমিংয়ের অনুরোধ করে এবং তারপর ফলাফলগুলোর মধ্যে দিয়ে পুনরাবৃত্তি করে:
সুইফট
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() এক্সটেনশন ফাংশনটি ব্যবহার করার জন্য, অ্যাপের build.gradle(.kts) ফাইলে org.jetbrains.kotlinx:kotlinx-coroutines-reactive লাইব্রেরিটিকে একটি ডিপেন্ডেন্সি হিসেবে যোগ করুন।
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 অপশনটি ব্যবহার করুন।
ডিফল্টরূপে, কলযোগ্য ফাংশনগুলিতে সমস্ত অরিজিন থেকে অনুরোধ অনুমোদনের জন্য CORS কনফিগার করা থাকে। কিছু ক্রস-অরিজিন অনুরোধের অনুমতি দিতে, কিন্তু সবগুলোর নয়, নির্দিষ্ট ডোমেইন বা রেগুলার এক্সপ্রেশনের একটি তালিকা পাস করুন যেগুলোকে অনুমতি দেওয়া উচিত। উদাহরণস্বরূপ:
নোড.জেএস
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 Status codes- এ তালিকাভুক্ত মানগুলোর মধ্যে যেকোনো একটি হতে পারে। ত্রুটিগুলোতে একটি স্ট্রিং ' message ও থাকে, যা ডিফল্টভাবে একটি খালি স্ট্রিং হয়। এগুলোতে একটি ঐচ্ছিক details ফিল্ডও থাকতে পারে, যার মান ইচ্ছামতো হতে পারে। যদি আপনার ফাংশনগুলো থেকে HTTPS ত্রুটি ছাড়া অন্য কোনো ত্রুটি থ্রো করা হয়, তবে আপনার ক্লায়েন্ট তার পরিবর্তে 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.");
}
পাইথন
# 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
ফাংশন ডিপ্লয় করার সময় যদি পারমিশন সংক্রান্ত ত্রুটি দেখা দেয়, তাহলে নিশ্চিত করুন যে ডিপ্লয়মেন্ট কমান্ডগুলো চালনাকারী ব্যবহারকারীকে যথাযথ IAM রোলগুলো বরাদ্দ করা আছে।
আপনার ক্লায়েন্ট ডেভেলপমেন্ট পরিবেশ সেট আপ করুন
পূর্বশর্তগুলো পূরণ হয়েছে কিনা তা নিশ্চিত করুন, তারপর আপনার অ্যাপে প্রয়োজনীয় ডিপেন্ডেন্সি এবং ক্লায়েন্ট লাইব্রেরিগুলো যোগ করুন।
iOS+
আপনার Apple অ্যাপে Firebase যোগ করতে নির্দেশাবলী অনুসরণ করুন।
ফায়ারবেস ডিপেন্ডেন্সিগুলো ইনস্টল ও পরিচালনা করতে সুইফট প্যাকেজ ম্যানেজার ব্যবহার করুন।
- Xcode-এ আপনার অ্যাপ প্রজেক্টটি খুলে, File > Add Packages- এ যান।
- অনুরোধ করা হলে, Firebase Apple প্ল্যাটফর্ম SDK রিপোজিটরিটি যোগ করুন:
- Cloud Functions লাইব্রেরিটি নির্বাচন করুন।
- আপনার টার্গেটের বিল্ড সেটিংসের ' Other Linker Flags' সেকশনে
-ObjCফ্ল্যাগটি যোগ করুন। - কাজ শেষ হলে, Xcode স্বয়ংক্রিয়ভাবে ব্যাকগ্রাউন্ডে আপনার ডিপেন্ডেন্সিগুলো রিজলভ ও ডাউনলোড করা শুরু করবে।
https://github.com/firebase/firebase-ios-sdk.git
Web
- আপনার ওয়েব অ্যাপে ফায়ারবেস যোগ করতে নির্দেশাবলী অনুসরণ করুন। আপনার টার্মিনাল থেকে নিম্নলিখিত কমান্ডটি চালাতে ভুলবেন না:
npm install firebase@12.11.0 --save
ম্যানুয়ালি ফায়ারবেস কোর এবং 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);
অ্যান্ড্রয়েড
আপনার অ্যান্ড্রয়েড অ্যাপে ফায়ারবেস যুক্ত করতে নির্দেশাবলী অনুসরণ করুন।
আপনার মডিউল (অ্যাপ-লেভেল) গ্রেডল ফাইলে (সাধারণত
<project>/<app-module>/build.gradle.ktsঅথবা<project>/<app-module>/build.gradle), অ্যান্ড্রয়েডের জন্য Cloud Functions লাইব্রেরির ডিপেন্ডেন্সি যোগ করুন। লাইব্রেরির ভার্সনিং নিয়ন্ত্রণের জন্য আমরা Firebase Android BoM ব্যবহার করার পরামর্শ দিই।dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.11.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 লাইব্রেরিগুলোর সামঞ্জস্যপূর্ণ সংস্করণ ব্যবহার করবে।
(বিকল্প) 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.0") }
ক্লায়েন্ট SDK শুরু করুন
Cloud Functions একটি ইনস্ট্যান্স শুরু করুন :
সুইফট
lazy var functions = Functions.functions()
উদ্দেশ্য-সি
@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();
ফাংশনটি কল করুন
সুইফট
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
}
}
উদ্দেশ্য-সি
[[_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;
সি++
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);
}
ঐক্য
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 কোড থাকে। আপনার কলযোগ্য ফাংশনে কীভাবে ত্রুটি পরিচালনা করতে হয়, তার জন্য নির্দেশিকা দেখুন।
সুইফট
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 (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);
}
সি++
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);
// ...
ঐক্য
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 সক্রিয় করা উচিত, যাতে এটি নিশ্চিত করা যায় যে শুধুমাত্র আপনার অ্যাপগুলোই আপনার কলযোগ্য ফাংশন এন্ডপয়েন্টগুলো অ্যাক্সেস করতে পারে।