Cloud Functions for Firebase আপনাকে সরাসরি Firebase অ্যাপ থেকে ফাংশন কল করতে দেয়। এইভাবে আপনার অ্যাপ থেকে কোনও ফাংশন কল করতে, Cloud Functions এ একটি HTTP Callable ফাংশন লিখুন এবং স্থাপন করুন, এবং তারপর আপনার অ্যাপ থেকে ফাংশনটি কল করার জন্য ক্লায়েন্ট লজিক যোগ করুন।
এটা মনে রাখা গুরুত্বপূর্ণ যে HTTP কলযোগ্য ফাংশনগুলি HTTP ফাংশনের মতো কিন্তু অভিন্ন নয় । HTTP কলযোগ্য ফাংশন ব্যবহার করার জন্য আপনাকে অবশ্যই আপনার প্ল্যাটফর্মের জন্য ক্লায়েন্ট SDK ব্যবহার করতে হবে ব্যাকএন্ড API (অথবা প্রোটোকল বাস্তবায়ন) সহ। কলযোগ্য ফাংশনগুলির HTTP ফাংশন থেকে এই মূল পার্থক্য রয়েছে:
- কলেবলের ক্ষেত্রে, Firebase Authentication টোকেন, FCM টোকেন এবং App Check টোকেন, যখন উপলব্ধ থাকে, স্বয়ংক্রিয়ভাবে অনুরোধে অন্তর্ভুক্ত হয়ে যায়।
- ট্রিগারটি স্বয়ংক্রিয়ভাবে অনুরোধের বডি ডিসিরিয়ালাইজ করে এবং প্রমাণীকরণ টোকেনগুলিকে বৈধ করে।
Cloud Functions জন্য Firebase SDK দ্বিতীয় প্রজন্ম এবং উচ্চতর HTTPS কলযোগ্য ফাংশনগুলিকে সমর্থন করার জন্য এই ফায়ারবেস ক্লায়েন্ট SDK ন্যূনতম সংস্করণগুলির সাথে আন্তঃকার্যকর হয়:
- Apple প্ল্যাটফর্মের জন্য Firebase SDK 12.4.0
- Android 22.0.1 এর জন্য Firebase SDK
- ফায়ারবেস মডুলার ওয়েব SDK সংস্করণ 9.7.0
যদি আপনি একটি অসমর্থিত প্ল্যাটফর্মে তৈরি একটি অ্যাপে অনুরূপ কার্যকারিতা যোগ করতে চান, তাহলে 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
আপনার প্ল্যাটফর্মের জন্য অনুরোধ হ্যান্ডলার ( functions.https.onCall
) অথবা on_call
) ব্যবহার করে একটি HTTPS কলযোগ্য ফাংশন তৈরি করুন। এই পদ্ধতিতে একটি অনুরোধ প্যারামিটার লাগে:
নোড.জেএস
// 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
প্যারামিটারে ক্লায়েন্ট অ্যাপ থেকে প্রেরিত ডেটার পাশাপাশি প্রমাণীকরণের অবস্থা সম্পর্কিত অতিরিক্ত প্রসঙ্গ থাকে auth
উদাহরণস্বরূপ, একটি কলযোগ্য ফাংশন যা 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 এর ক্ষেত্রে, একটি প্রতিশ্রুতি প্রদান করতে হবে যা একটি মান দিয়ে সমাধান করে। অন্যথায়, ক্লায়েন্টের কাছে ডেটা ফেরত পাঠানোর আগেই ফাংশনটি বন্ধ হয়ে যেতে পারে। নির্দেশিকাটির জন্য 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
মিথ্যা হয়, তাহলে আপনি পৃথক অংশ প্রস্তুত বা পাঠানোর সাথে সম্পর্কিত যে কোনও রিসোর্স-ইনটেনসিভ কাজ এড়িয়ে যাওয়ার সিদ্ধান্ত নিতে পারেন, কারণ ক্লায়েন্ট ক্রমবর্ধমান ডেলিভারি আশা করছেন না।
স্ট্রিমিং ফলাফল পান
একটি সাধারণ পরিস্থিতিতে, ক্লায়েন্ট .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
এ সেট করুন।
ত্রুটিগুলি পরিচালনা করুন
ক্লায়েন্ট যাতে কার্যকর ত্রুটির বিবরণ পায় তা নিশ্চিত করার জন্য, একটি কলেবল থেকে ত্রুটিগুলি ফেরত পাঠান (অথবা Node.js এর জন্য একটি প্রতিশ্রুতি প্রত্যাখ্যান করে) functions.https.HttpsError
অথবা https_fn.HttpsError
এর একটি উদাহরণ দিয়ে। ত্রুটিটিতে একটি code
অ্যাট্রিবিউট রয়েছে যা gRPC Status কোডগুলিতে তালিকাভুক্ত মানগুলির মধ্যে একটি হতে পারে। ত্রুটিগুলিতে একটি string 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 ভূমিকাগুলি স্থাপন কমান্ড চালানো ব্যবহারকারীর জন্য নির্ধারিত হয়েছে।
আপনার ক্লায়েন্ট ডেভেলপমেন্ট পরিবেশ সেট আপ করুন
নিশ্চিত করুন যে আপনি যেকোনো পূর্বশর্ত পূরণ করেছেন, তারপর আপনার অ্যাপে প্রয়োজনীয় নির্ভরতা এবং ক্লায়েন্ট লাইব্রেরি যোগ করুন।
আইওএস+
আপনার অ্যাপল অ্যাপে Firebase যোগ করার জন্য নির্দেশাবলী অনুসরণ করুন।
ফায়ারবেস নির্ভরতা ইনস্টল এবং পরিচালনা করতে সুইফট প্যাকেজ ম্যানেজার ব্যবহার করুন।
- Xcode-এ, আপনার অ্যাপ প্রজেক্ট খোলা থাকা অবস্থায়, File > Add Packages- এ নেভিগেট করুন।
- অনুরোধ করা হলে, Firebase Apple platforms SDK সংগ্রহস্থল যোগ করুন:
- Cloud Functions লাইব্রেরিটি নির্বাচন করুন।
- আপনার টার্গেটের বিল্ড সেটিংসের অন্যান্য লিঙ্কার ফ্ল্যাগ বিভাগে
-ObjC
ফ্ল্যাগ যোগ করুন। - শেষ হয়ে গেলে, Xcode স্বয়ংক্রিয়ভাবে ব্যাকগ্রাউন্ডে আপনার নির্ভরতাগুলি সমাধান এবং ডাউনলোড করা শুরু করবে।
https://github.com/firebase/firebase-ios-sdk.git
Web
- আপনার ওয়েব অ্যাপে Firebase যোগ করার জন্য নির্দেশাবলী অনুসরণ করুন। আপনার টার্মিনাল থেকে নিম্নলিখিত কমান্ডটি চালাতে ভুলবেন না:
npm install firebase@12.4.0 --save
ম্যানুয়ালি Firebase কোর এবং 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);
অ্যান্ড্রয়েড
আপনার অ্যান্ড্রয়েড অ্যাপে Firebase যোগ করার জন্য নির্দেশাবলী অনুসরণ করুন।
আপনার মডিউল (অ্যাপ-লেভেল) গ্র্যাডেল ফাইলে (সাধারণত
<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.4.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 লাইব্রেরি নির্ভরতা যোগ করুন
যদি আপনি 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.0.1") }
ক্লায়েন্ট 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 সক্ষম করা উচিত যাতে শুধুমাত্র আপনার অ্যাপগুলি আপনার কলযোগ্য ফাংশন এন্ডপয়েন্টগুলি অ্যাক্সেস করতে পারে তা নিশ্চিত করতে সহায়তা করে।