Cloud Firestore ডেটা বান্ডেল হল আপনার তৈরি করা স্ট্যাটিক ডেটা ফাইল Cloud Firestore ডকুমেন্ট এবং কোয়েরি স্ন্যাপশট, এবং আপনার দ্বারা প্রকাশিত CDN, হোস্টিং পরিষেবা বা অন্যান্য সমাধান। ডেটা বান্ডেলে আপনার ক্লায়েন্ট অ্যাপে প্রদান করতে চাওয়া ডকুমেন্ট এবং যে কোয়েরি থেকে সেগুলি জেনারেট হয়েছে তার মেটাডেটা, দুটিই অন্তর্ভুক্ত থাকে। আপনি নেটওয়ার্ক বা লোকাল স্টোরেজ থেকে বান্ডেল ডাউনলোড করতে ক্লায়েন্ট SDK ব্যবহার করেন, যার পরে আপনি Cloud Firestore লোকাল ক্যাশেতে বান্ডেল ডেটা লোড করেন। বান্ডেল লোড হয়ে গেলে, ক্লায়েন্ট অ্যাপ লোকাল ক্যাশে বা ব্যাকএন্ড থেকে ডকুমেন্ট কোয়েরি করতে পারে।
ডেটা বান্ডেলের মাধ্যমে, আপনার অ্যাপ সাধারণ কোয়েরির ফলাফল আরও দ্রুত লোড করতে পারে, কারণ স্টার্ট-আপে ডকুমেন্ট উপলভ্য থাকে, তাই Cloud Firestore ব্যাকএন্ডে কল করার প্রয়োজন হয় না। ফলাফল স্থানীয় ক্যাশ থেকে লোড করা হলে, আপনিও অ্যাক্সেস খরচ কমানোর সুবিধা পাবেন। একই প্রাথমিক ১০০টি ডকুমেন্ট কোয়েরি করার জন্য এক মিলিয়ন অ্যাপ ইনস্ট্যান্সের জন্য পেমেন্ট করার পরিবর্তে, আপনি শুধুমাত্র সেই ১০০টি ডকুমেন্ট বান্ডেল করার জন্য প্রয়োজনীয় কোয়েরির জন্য পেমেন্ট করেন।
Cloud Firestore ডেটা বান্ডেল অন্যান্য Firebase ব্যাকএন্ড প্রোডাক্টের সাথে ভালভাবে কাজ করার জন্য তৈরি করা হয়েছে। ইন্টিগ্রেটেড সলিউশন দেখুন যেখানে Cloud Functions-এর মাধ্যমে বান্ডেল তৈরি করা হয় এবং Firebase Hosting-এর মাধ্যমে ব্যবহারকারীদের কাছে পৌঁছে দেওয়া হয়।
আপনার অ্যাপের সাথে বান্ডেল ব্যবহার করার জন্য তিনটি ধাপ রয়েছে:
- অ্যাডমিন SDK-এর মাধ্যমে বান্ডেল তৈরি করা
- লোকাল স্টোরেজ বা CDN থেকে বান্ডেল পরিবেশন করা হচ্ছে
- ক্লায়েন্টে বান্ডেল লোড করা হচ্ছে
ডেটা বান্ডেল কী?
ডেটা বান্ডেল হল একটি স্ট্যাটিক বাইনারি ফাইল যা আপনি এক বা একাধিক ডকুমেন্ট এবং/অথবা কোয়েরি স্ন্যাপশট প্যাকেজ করার জন্য তৈরি করেছেন এবং যেখান থেকে আপনি নামযুক্ত কোয়েরি এক্সট্র্যাক্ট করতে পারবেন। আমরা নিচে আলোচনা করেছি যে, সার্ভার-সাইড SDK আপনাকে বান্ডেল তৈরি করতে দেয় এবং ক্লায়েন্ট SDK আপনাকে লোকাল ক্যাশে বান্ডেল লোড করার পদ্ধতি প্রদান করে।
নামযুক্ত কোয়েরি হল বান্ডেলের একটি বিশেষ শক্তিশালী ফিচার। নেমড কোয়েরি হল
Query অবজেক্ট যা আপনি বান্ডেল থেকে এক্সট্র্যাক্ট করতে পারবেন, তারপর ক্যাশে বা ব্যাকএন্ড থেকে ডেটা কোয়েরি করার জন্য
অবিলম্বে ব্যবহার করতে পারবেন, যেমন আপনি সাধারণত আপনার অ্যাপের যেকোনও অংশে করেন যা
Cloud Firestore-এর সাথে যোগাযোগ করে।
সার্ভারে ডেটা বান্ডেল তৈরি করা হচ্ছে
Node.js বা Java অ্যাডমিন SDK ব্যবহার করলে, বান্ডেলে কী অন্তর্ভুক্ত করতে হবে এবং কীভাবে সেগুলি পরিবেশন করতে হবে তার উপর আপনার সম্পূর্ণ নিয়ন্ত্রণ থাকে।
Node.js
var bundleId = "latest-stories"; var bundle = firestore.bundle(bundleId); var docSnapshot = await firestore.doc('stories/stories').get(); var querySnapshot = await firestore.collection('stories').get(); // Build the bundle // Note how querySnapshot is named "latest-stories-query" var bundleBuffer = bundle.add(docSnapshot); // Add a document .add('latest-stories-query', querySnapshot) // Add a named query. .build()
জাভা
Firestore db = FirestoreClient.getFirestore(app); // Query the 50 latest stories QuerySnapshot latestStories = db.collection("stories") .orderBy("timestamp", Direction.DESCENDING) .limit(50) .get() .get(); // Build the bundle from the query results FirestoreBundle bundle = db.bundleBuilder("latest-stories") .add("latest-stories-query", latestStories) .build();
Python
from google.cloud import firestore from google.cloud.firestore_bundle import FirestoreBundle db = firestore.Client() bundle = FirestoreBundle("latest-stories") doc_snapshot = db.collection("stories").document("news-item").get() query = db.collection("stories")._query() # Build the bundle # Note how `query` is named "latest-stories-query" bundle_buffer: str = bundle.add_document(doc_snapshot).add_named_query( "latest-stories-query", query, ).build()
পরিষেবা ডেটা বান্ডেল
আপনি CDN থেকে বা ডাউনলোড করে আপনার ক্লায়েন্ট অ্যাপে বান্ডেল পরিবেশন করতে পারেন যেমন, Cloud Storage থেকে।
ধরে নিন যে আগের বিভাগে তৈরি করা বান্ডেলটি bundle.txtনামের একটি ফাইলে সেভ করা হয়েছে এবং একটি সার্ভারে পোস্ট করা হয়েছে। এই
বান্ডেল ফাইলটি আপনি ওয়েবে পরিবেশন করতে পারেন এমন অন্য যেকোনও অ্যাসেটের মতো, যেমন এখানে দেখানো হয়েছে
একটি সাধারণ Node.js Express অ্যাপের জন্য।
const fs = require('fs');
const server = require('http').createServer();
server.on('request', (req, res) => {
const src = fs.createReadStream('./bundle.txt');
src.pipe(res);
});
server.listen(8000);
ক্লায়েন্টে ডেটা বান্ডেল লোড করা হচ্ছে
আপনি রিমোট সার্ভার থেকে Firestore বান্ডেল ফেচ করে লোড করেন, তা HTTP অনুরোধ করে, স্টোরেজ API কল করে বা নেটওয়ার্কে বাইনারি ফাইল ফেচ করার জন্য অন্য কোনও টেকনিক ব্যবহার করে হতে পারে।
ফেচ করা হয়ে গেলে, Cloud Firestore ক্লায়েন্ট SDK ব্যবহার করে, আপনার অ্যাপ
loadBundle পদ্ধতিকে কল করে, যা একটি টাস্ক ট্র্যাকিং অবজেক্ট রিটার্ন করে, যার
সম্পূর্ণতা আপনি প্রমিজের স্ট্যাটাস মনিটর করার মতোই মনিটর করতে পারবেন।
বান্ডেল লোড করার টাস্ক সম্পূর্ণ হলে, বান্ডেলের কন্টেন্ট লোকাল ক্যাশেতে উপলভ্য হয়।
Web
import { loadBundle, namedQuery, getDocsFromCache } from "firebase/firestore"; async function fetchFromBundle() { // Fetch the bundle from Firebase Hosting, if the CDN cache is hit the 'X-Cache' // response header will be set to 'HIT' const resp = await fetch('/createBundle'); // Load the bundle contents into the Firestore SDK await loadBundle(db, resp.body); // Query the results from the cache const query = await namedQuery(db, 'latest-stories-query'); const storiesSnap = await getDocsFromCache(query); // Use the results // ... }
Web
// If you are using module bundlers. import firebase from "firebase/compat/app"; import "firebase/compat/firestore"; // ... async function fetchFromBundle() { // Fetch the bundle from Firebase Hosting, if the CDN cache is hit the 'X-Cache' // response header will be set to 'HIT' const resp = await fetch('/createBundle'); // Load the bundle contents into the Firestore SDK await db.loadBundle(resp.body); // Query the results from the cache // Note: omitting "source: cache" will query the Firestore backend. const query = await db.namedQuery('latest-stories-query'); const storiesSnap = await query.get({ source: 'cache' }); // Use the results // ... }
Swift
// Utility function for errors when loading bundles. func bundleLoadError(reason: String) -> NSError { return NSError(domain: "FIRSampleErrorDomain", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: reason]) } func fetchRemoteBundle(for firestore: Firestore, from url: URL) async throws -> LoadBundleTaskProgress { guard let inputStream = InputStream(url: url) else { let error = self.bundleLoadError(reason: "Unable to create stream from the given url: \(url)") throw error } return try await firestore.loadBundle(inputStream) } // Fetches a specific named query from the provided bundle. func loadQuery(named queryName: String, fromRemoteBundle bundleURL: URL, with store: Firestore) async throws -> Query { let _ = try await fetchRemoteBundle(for: store, from: bundleURL) if let query = await store.getQuery(named: queryName) { return query } else { throw bundleLoadError(reason: "Could not find query named \(queryName)") } } // Load a query and fetch its results from a bundle. func runStoriesQuery() async { let queryName = "latest-stories-query" let firestore = Firestore.firestore() let remoteBundle = URL(string: "https://example.com/createBundle")! do { let query = try await loadQuery(named: queryName, fromRemoteBundle: remoteBundle, with: firestore) let snapshot = try await query.getDocuments() print(snapshot) // handle query results } catch { print(error) } }
Objective-C
// Utility function for errors when loading bundles. - (NSError *)bundleLoadErrorWithReason:(NSString *)reason { return [NSError errorWithDomain:@"FIRSampleErrorDomain" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey: reason}]; } // Loads a remote bundle from the provided url. - (void)fetchRemoteBundleForFirestore:(FIRFirestore *)firestore fromURL:(NSURL *)url completion:(void (^)(FIRLoadBundleTaskProgress *_Nullable, NSError *_Nullable))completion { NSInputStream *inputStream = [NSInputStream inputStreamWithURL:url]; if (inputStream == nil) { // Unable to create input stream. NSError *error = [self bundleLoadErrorWithReason: [NSString stringWithFormat:@"Unable to create stream from the given url: %@", url]]; completion(nil, error); return; } [firestore loadBundleStream:inputStream completion:^(FIRLoadBundleTaskProgress * _Nullable progress, NSError * _Nullable error) { if (progress == nil) { completion(nil, error); return; } if (progress.state == FIRLoadBundleTaskStateSuccess) { completion(progress, nil); } else { NSError *concreteError = [self bundleLoadErrorWithReason: [NSString stringWithFormat: @"Expected bundle load to be completed, but got %ld instead", (long)progress.state]]; completion(nil, concreteError); } completion(nil, nil); }]; } // Loads a bundled query. - (void)loadQueryNamed:(NSString *)queryName fromRemoteBundleURL:(NSURL *)url withFirestore:(FIRFirestore *)firestore completion:(void (^)(FIRQuery *_Nullable, NSError *_Nullable))completion { [self fetchRemoteBundleForFirestore:firestore fromURL:url completion:^(FIRLoadBundleTaskProgress *progress, NSError *error) { if (error != nil) { completion(nil, error); return; } [firestore getQueryNamed:queryName completion:^(FIRQuery *query) { if (query == nil) { NSString *errorReason = [NSString stringWithFormat:@"Could not find query named %@", queryName]; NSError *error = [self bundleLoadErrorWithReason:errorReason]; completion(nil, error); return; } completion(query, nil); }]; }]; } - (void)runStoriesQuery { NSString *queryName = @"latest-stories-query"; FIRFirestore *firestore = [FIRFirestore firestore]; NSURL *bundleURL = [NSURL URLWithString:@"https://example.com/createBundle"]; [self loadQueryNamed:queryName fromRemoteBundleURL:bundleURL withFirestore:firestore completion:^(FIRQuery *query, NSError *error) { // Handle query results }]; }
Kotlin
@Throws(IOException::class) fun getBundleStream(urlString: String?): InputStream { val url = URL(urlString) val connection = url.openConnection() as HttpURLConnection return connection.inputStream } @Throws(IOException::class) fun fetchFromBundle() { val bundleStream = getBundleStream("https://example.com/createBundle") val loadTask = db.loadBundle(bundleStream) // Chain the following tasks // 1) Load the bundle // 2) Get the named query from the local cache // 3) Execute a get() on the named query loadTask.continueWithTask<Query> { task -> // Close the stream bundleStream.close() // Calling .result propagates errors val progress = task.getResult(Exception::class.java) // Get the named query from the bundle cache db.getNamedQuery("latest-stories-query") }.continueWithTask { task -> val query = task.getResult(Exception::class.java)!! // get() the query results from the cache query.get(Source.CACHE) }.addOnCompleteListener { task -> if (!task.isSuccessful) { Log.w(TAG, "Bundle loading failed", task.exception) return@addOnCompleteListener } // Get the QuerySnapshot from the bundle val storiesSnap = task.result // Use the results // ... } }
Java
public InputStream getBundleStream(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); return connection.getInputStream(); } public void fetchBundleFrom() throws IOException { final InputStream bundleStream = getBundleStream("https://example.com/createBundle"); LoadBundleTask loadTask = db.loadBundle(bundleStream); // Chain the following tasks // 1) Load the bundle // 2) Get the named query from the local cache // 3) Execute a get() on the named query loadTask.continueWithTask(new Continuation<LoadBundleTaskProgress, Task<Query>>() { @Override public Task<Query> then(@NonNull Task<LoadBundleTaskProgress> task) throws Exception { // Close the stream bundleStream.close(); // Calling getResult() propagates errors LoadBundleTaskProgress progress = task.getResult(Exception.class); // Get the named query from the bundle cache return db.getNamedQuery("latest-stories-query"); } }).continueWithTask(new Continuation<Query, Task<QuerySnapshot>>() { @Override public Task<QuerySnapshot> then(@NonNull Task<Query> task) throws Exception { Query query = task.getResult(Exception.class); // get() the query results from the cache return query.get(Source.CACHE); } }).addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (!task.isSuccessful()) { Log.w(TAG, "Bundle loading failed", task.getException()); return; } // Get the QuerySnapshot from the bundle QuerySnapshot storiesSnap = task.getResult(); // Use the results // ... } }); }
Dart
// Get a bundle from a server final url = Uri.https('example.com', '/create-bundle'); final response = await http.get(url); String body = response.body; final buffer = Uint8List.fromList(body.codeUnits); // Load a bundle from a buffer LoadBundleTask task = FirebaseFirestore.instance.loadBundle(buffer); await task.stream.toList(); // Use the cached named query final results = await FirebaseFirestore.instance.namedQueryGet( "latest-stories-query", options: const GetOptions( source: Source.cache, ), );
C++
db->LoadBundle("bundle_name", [](const LoadBundleTaskProgress& progress) { switch(progress.state()) { case LoadBundleTaskProgress::State::kError: { // The bundle load has errored. Handle the error in the returned future. return; } case LoadBundleTaskProgress::State::kInProgress: { std::cout << "Bytes loaded from bundle: " << progress.bytes_loaded() << std::endl; break; } case LoadBundleTaskProgress::State::kSuccess: { std::cout << "Bundle load succeeeded" << std::endl; break; } } }).OnCompletion([db](const Future<LoadBundleTaskProgress>& future) { if (future.error() != Error::kErrorOk) { // Handle error... return; } const std::string& query_name = "latest_stories_query"; db->NamedQuery(query_name).OnCompletion([](const Future<Query>& query_future){ if (query_future.error() != Error::kErrorOk) { // Handle error... return; } const Query* query = query_future.result(); query->Get().OnCompletion([](const Future<QuerySnapshot> &){ // ... }); }); });
মনে রাখবেন যে আপনি যদি ৩০ মিনিটের কম আগে তৈরি করা বান্ডেল থেকে নামযুক্ত কোয়েরি লোড করেন, একবার আপনি ক্যাশের পরিবর্তে ব্যাকএন্ড থেকে পড়ার জন্য এটি ব্যবহার করলে, ব্যাকএন্ডে যা স্টোর করা আছে তার সাথে মিল করার জন্য ডকুমেন্ট আপডেট করতে প্রয়োজনীয় ডেটাবেস রিডের জন্য আপনাকে শুধুমাত্র পেমেন্ট করতে হবে; অর্থাৎ, আপনি শুধুমাত্র ডেল্টার জন্য পেমেন্ট করবেন।
এরপর কী করতে হবে?
ক্লায়েন্ট সাইড (Apple, Android, ওয়েব) এবং সার্ভার সাইডের (Node.js) জন্য ডেটা বান্ডেল API রেফারেন্স ডকুমেন্টেশন দেখুন।
আপনি আগে থেকে না দেখে থাকলে, Cloud Functions এবং Firebase Hosting বান্ডেল তৈরি ও পরিবেশন করার সমাধান দেখুন।