আপনার অ্যাপ থেকে কল ফাংশন

Cloud Functions for Firebase ক্লায়েন্ট SDK আপনাকে সরাসরি Firebase অ্যাপ থেকে ফাংশন কল করতে দেয়। এইভাবে আপনার অ্যাপ থেকে কোনও ফাংশন কল করতে, Cloud Functions-এ HTTP কল করা যায় এমন ফাংশন লিখুন ও প্রয়োগ করুন এবং তারপরে আপনার অ্যাপ থেকে ফাংশন কল করার জন্য ক্লায়েন্ট লজিক যোগ করুন।

মনে রাখা গুরুত্বপূর্ণ যে HTTP কল করা যায় এমন ফাংশনগুলি একই রকম হলেও HTTP ফাংশনের সাথে একই নয়। HTTP কল করা যায় এমন ফাংশন ব্যবহার করতে হলে আপনাকে অবশ্যই ব্যাকএন্ড API (বা প্রোটোকল প্রয়োগ করুন)-এর সাথে আপনার প্ল্যাটফর্মের জন্য ক্লায়েন্ট SDK ব্যবহার করতে হবে। কল করার উপযুক্ত ফাংশন ও HTTP ফাংশনের মধ্যে এইসব মূল পার্থক্য রয়েছে:

  • কলযোগ্য, Firebase Authentication টোকেন, FCM টোকেন ও App Check টোকেন উপলভ্য থাকলে, সেগুলি অটোমেটিক অনুরোধে অন্তর্ভুক্ত করা হয়।
  • ট্রিগারটি অটোমেটিক অনুরোধের বডিকে ডিসিরিয়ালাইজ করে এবং যাচাইকরণ টোকেনকে যাচাই করে।

HTTPS কল করার উপযুক্ত ফাংশন কাজ করানোর জন্য Firebase 2nd gen ও তার পরের ভার্সনের SDK Cloud Functions-এর সাথে এইসব Firebase ক্লায়েন্ট SDK-এর ন্যূনতম ভার্সন ইন্টারঅপারেট করে:

  • Firebase Apple প্ল্যাটফর্মের জন্য SDK 13.0.0
  • Firebase Android 22.1.1-এর জন্য SDK
  • Firebase Modular Web SDK v. 9.7.0

আপনি যদি কোনও কাজ করে না এমন প্ল্যাটফর্মে তৈরি অ্যাপে একই ধরনের ফাংশনালিটি যোগ করতে চান, তাহলে https.onCall-এর জন্য প্রোটোকল স্পেসিফিকেশন দেখুন। এই গাইডের বাকি অংশে Apple প্ল্যাটফর্ম, Android, ওয়েব, C++ ও Unity-র জন্য HTTP কল করা যায় এমন ফাংশন কীভাবে লিখতে, ডিপ্লয় করতে ও কল করতে হয় সেই বিষয়ে নির্দেশাবলী দেওয়া আছে।

কল করা যায় এমন ফাংশন লেখা ও ডেপ্লয় করা

এই বিভাগে দেওয়া কোডের উদাহরণগুলি একটি সম্পূর্ণ দ্রুত শুরু করার স্যাম্পেলের উপর ভিত্তি করে তৈরি করা হয়েছে, যা দেখায় যে কীভাবে কোনও সার্ভার-সাইড ফাংশনে অনুরোধ পাঠাতে হয় এবং কোনও একটি ক্লায়েন্ট 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 অ্যাটেস্টেশন অ্যাটাচ করতে পারেন, যাতে বিলিং ফ্রড বা ফিশিংয়ের মতো অপব্যবহার থেকে আপনার ব্যাকএন্ড রিসোর্স সুরক্ষিত রাখতে সাহায্য করে। Cloud Functions-এর জন্য App Check এনফোর্সমেন্ট চালু করুন দেখুন।

ফলাফল ফেরত পাঠানো

ক্লায়েন্টকে ডেটা ফেরত পাঠাতে, 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-এ, এটি জাভাস্ক্রিপ্ট প্রমিস ব্যবহার করে অ্যাসিঙ্ক্রোনাসভাবে করা যেতে পারে:

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-এর ক্ষেত্রে, একটি Promise রিটার্ন করতে হবে যা একটি ভ্যালু সহ রেজোলভ হয়। অন্যথায়, ক্লায়েন্টকে ডেটা পাঠানোর আগেই ফাংশনটি বন্ধ হয়ে যেতে পারে। নির্দেশিকার জন্য ফাংশন বন্ধ করা লিঙ্ক দেখুন।

স্ট্রিমিং ফলাফল পাঠানো ও পাওয়া

কল করা যায় এমন ফাংশনে স্ট্রিমিং ফলাফল ম্যানেজ করার মেকানিজম থাকে। আপনার যদি এমন কোনও ব্যবহারের ক্ষেত্র থাকে যেখানে স্ট্রিমিংয়ের প্রয়োজন হয়, তাহলে আপনি কল করা যায় এমন অনুরোধে স্ট্রিমিং কনফিগার করতে পারেন এবং তারপরে ফাংশন কল করার জন্য ক্লায়েন্ট 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() কীভাবে কাজ করে তা ক্লায়েন্টের অনুরোধের নির্দিষ্ট বিবরণের উপর নির্ভর করে:

  1. ক্লায়েন্ট স্ট্রিমিং রেসপন্স চাইলে: response.sendChunk(data) সঙ্গে সঙ্গে ডেটা পিস পাঠায়।

  2. ক্লায়েন্ট স্ট্রিমিং রেসপন্স না চাইলে: 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() এক্সটেনশন ফাংশন ব্যবহার করতে, অ্যাপের 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 কনফিগার করা থাকে যাতে সব অরিজিন থেকে আসা অনুরোধ গ্রহণ করা যায়। কিছু ক্রস-অরিজিন অনুরোধ অনুমোদন করতে, কিন্তু সব নয়, অনুমোদিত হতে হবে এমন নির্দিষ্ট ডোমেন বা রেগুলার এক্সপ্রেশনের একটি তালিকা পাস করুন। যেমন:

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 হিসেবে সেট করুন।

সমস্যা ম্যানেজ করা

ক্লায়েন্ট যাতে সমস্যার ব্যাপারে বিস্তারিত তথ্য পায় তা নিশ্চিত করতে, কল করা যায় এমন ফাংশন থেকে সমস্যা ফেরত দিন। এর জন্য 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.",
    )

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

ফাংশন ডেপ্লয় করার সময় অনুমতির ব্যাপারে কোনও সমস্যা হলে, নিশ্চিত করুন যে ডেপ্লয়মেন্ট কমান্ড রান করা ব্যবহারকারীকে উপযুক্ত IAM ভূমিকা অ্যাসাইন করা হয়েছে।

আপনার ক্লায়েন্ট ডেভেলপমেন্ট এনভায়রনমেন্ট সেট-আপ করা

আপনি পূর্বশর্ত পূরণ করেছেন কিনা তা নিশ্চিত করুন, তারপর আপনার অ্যাপে প্রয়োজনীয় ডিপেন্ডেন্সি এবং ক্লায়েন্ট লাইব্রেরি যোগ করুন।

iOS+

আপনার Apple অ্যাপে Firebase যোগ করতে নির্দেশাবলী অনুসরণ করুন।

Firebase ডিপেন্ডেন্সি ইনস্টল ও ম্যানেজ করতে Swift Package Manager ব্যবহার করুন।

  1. Xcode-এ, আপনার অ্যাপ প্রোজেক্ট খোলা থাকা অবস্থায়, ফাইল > প্যাকেজ যোগ করুন বিকল্পে নেভিগেট করুন।
  2. প্রম্পট করা হলে, Firebase Apple প্ল্যাটফর্ম SDK রিপোজিটরি যোগ করুন:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Cloud Functions লাইব্রেরি বেছে নিন।
  5. আপনার টার্গেটের বিল্ড সেটিংসের অন্যান্য লিঙ্কার ফ্ল্যাগ বিভাগে -ObjC ফ্ল্যাগ যোগ করুন।
  6. এটি সম্পূর্ণ হয়ে গেলে, Xcode অটোমেটিক আপনার ডিপেন্ডেন্সি ব্যাকগ্রাউন্ডে সমাধান ও ডাউনলোড করা শুরু করবে।

Web

  1. আপনার ওয়েব অ্যাপে Firebase যোগ করতে নির্দেশাবলী অনুসরণ করুন। আপনার টার্মিনাল থেকে নিম্নলিখিত কমান্ড রান করতে ভুলবেন না:
    npm install firebase@12.19.0 --save
  2. ম্যানুয়ালি Firebase core ও Cloud Functions দুটিই প্রয়োজন:

     import { initializeApp } from 'firebase/app';
     import { getFunctions } from 'firebase/functions';
    
     const app = initializeApp({
         projectId: '### CLOUD FUNCTIONS PROJECT ID ###',
         apiKey: '### FIREBASE API KEY ###',
         authDomain: '### FIREBASE AUTH DOMAIN ###',
       });
     const functions = getFunctions(app);

Android

  1. আপনার Android অ্যাপে Firebase যোগ করতে নির্দেশাবলী অনুসরণ করুন।

  2. আপনার মডিউল (অ্যাপ-লেভেল) Gradle ফাইলে (সাধারণত <project>/<app-module>/build.gradle.kts বা <project>/<app-module>/build.gradle), Android-এর জন্য Cloud Functions লাইব্রেরির ডিপেন্ডেন্সি যোগ করুন। লাইব্রেরি ভার্সনিং কন্ট্রোল করতে Firebase Android BoM ব্যবহার করার সাজেশন দিই।

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

ক্লায়েন্ট টাইম-আউট সেট করা

সাধারণত, Cloud Functions ক্লায়েন্ট SDK কল করা যায় এমন অনুরোধের জন্য ৭০ সেকেন্ডের টাইম-আউট ব্যবহার করে। কল করা যায় এমন কোনও ফাংশন সম্পূর্ণ হতে ৭০ সেকেন্ডের বেশি সময় লাগলে, ক্লায়েন্ট SDK DEADLINE_EXCEEDED (deadline-exceeded) সমস্যা সহ অনুরোধটি বাতিল করে দেয়—এমনকি আপনি যদি আরও বেশি সময় ধরে সার্ভার-সাইড টাইম-আউট কনফিগার করে থাকেন।

দীর্ঘ সময় ধরে কল করা যায় এমন ফাংশন যাতে কাজ করে, তার জন্য আপনাকে সার্ভার ও ক্লায়েন্ট দুটি জায়গাতেই টাইম-আউট বাড়াতে হবে:

  1. সার্ভার-সাইড ফাংশন টাইমআউট বাড়ান (দেখুন টাইমআউট ও মেমরি অ্যালোকেশন সেট করুন)।
  2. আপনার অ্যাপে কলযোগ্য রেফারেন্স কনফিগার করার সময় ক্লায়েন্ট-সাইড টাইম-আউট বাড়ান:

Swift

let callable = functions.httpsCallable("addMessage")
callable.timeoutInterval = 300  // 300 seconds (default is 70)
let result = try await callable.call(["text": text, "push": true])

Objective-C

FIRHTTPSCallable *callable = [self.functions HTTPSCallableWithName:@"addMessage"];
callable.timeoutInterval = 300;  // 300 seconds (default is 70)
[callable callWithObject:@{@"text": text, @"push": @YES}
              completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
  // ...
}];

Web

var addMessage = firebase.functions().httpsCallable('addMessage', {
  timeout: 300000,  // 300 seconds in milliseconds (default is 70000)
});
addMessage({ text: messageText })
  .then((result) => {
    // ...
  });

Web

import { getFunctions, httpsCallable } from "firebase/functions";

const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage', {
  timeout: 300000,  // 300 seconds in milliseconds (default is 70000)
});
const result = await addMessage({ text: messageText });

Kotlin

val callable = functions.getHttpsCallable("addMessage")
callable.setTimeout(300L, TimeUnit.SECONDS)
val result = callable.call(data).await()

Java

HttpsCallableReference callable = mFunctions.getHttpsCallable("addMessage");
callable.setTimeout(300L, TimeUnit.SECONDS);
Task<HttpsCallableResult> result = callable.call(data);

Dart

final callable = FirebaseFunctions.instance.httpsCallable(
  'addMessage',
  options: HttpsCallableOptions(
    timeout: const Duration(seconds: 300),
  ),
);
final result = await callable.call({
  'text': text,
  'push': true,
});

সাজেস্ট করা: App Check-এর মাধ্যমে অপব্যবহার প্রতিরোধ করা

আপনার অ্যাপ লঞ্চ করার আগে, App Check চালু করুন যাতে শুধুমাত্র আপনার অ্যাপই কল করা যায় এমন ফাংশন এন্ডপয়েন্ট অ্যাক্সেস করতে পারে।