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

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

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

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

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

  • Apple প্ল্যাটফর্মের জন্য Firebase SDK 13.1.1
  • Android 23.0.0-এর জন্য Firebase 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 প্যাকেজ ম্যানেজার ব্যবহার করুন।

আপনার Apple প্রোজেক্টে Firebase SDK যোগ করার বিভিন্ন উপায় সম্পর্কে জানতে
  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@13.2.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:35.1.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:23.0.0")
    }

ক্লায়েন্ট 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 চালু করা উচিত যাতে শুধু আপনার অ্যাপই কল করা যায় এমন ফাংশন এন্ডপয়েন্ট অ্যাক্সেস করতে পারে।