دسته‌های داده Cloud Firestore

دسته‌های داده Cloud Firestore فایل‌های داده ثابتی هستند که شما از عکس‌های آنی سند و پُرسمان Cloud Firestore ساخته‌اید و در CDN، سرویس میزبانی، یا راه‌حل دیگری منتشر کرده‌اید. دسته‌های داده شامل هر دو سندی است که می‌خواهید به برنامه‌های مشتری خود ارائه دهید و فراداده مربوط به پُرسمان‌هایی که آن‌ها را تولید کرده‌اند. از کیت‌های توسعه نرم‌افزار کارخواه برای بارگیری بسته‌ها ازطریق شبکه یا از فضای ذخیره‌سازی محلی استفاده می‌کنید، سپس داده‌های بسته را در حافظه نهان محلی Cloud Firestore بار می‌کنید. وقتی بسته‌ای بار می‌شود، برنامه کارخواه می‌تواند اسناد را از حافظه نهان محلی یا پس‌بست پُرسمان کند.

با دسته‌های داده، برنامه‌هایتان می‌توانند نتایج پُرسمان‌های رایج را زودتر بار کنند، زیرا اسناد در زمان راه‌اندازی دردسترس هستند و نیازی به تماس با Cloud Firestore backend نیست. اگر نتایج از حافظه پنهان محلی بار شود، از کاهش هزینه‌های دسترسی نیز بهره‌مند می‌شوید. به‌جای پرداخت هزینه برای یک میلیون نمونه برنامه برای پُرسمان همان ۱۰۰ سند اولیه، فقط هزینه پُرسمان‌های لازم برای دسته‌بندی آن ۱۰۰ سند را پرداخت می‌کنید.

Cloud Firestore بسته‌های داده برای کار کردن با دیگر محصولات Firebase در پس‌زمینه ساخته شده‌اند. راهکار یکپارچه را ببینید که در آن دسته‌ها توسط Cloud Functions ساخته می‌شوند و با Firebase Hosting به کاربران ارائه می‌شوند.

استفاده از بسته با برنامه شامل سه مرحله است:

  1. ساختن دسته با Admin SDK
  2. ارائه بسته از فضای ذخیره‌سازی محلی یا از CDN
  3. درحال بار کردن دسته‌ها در کارخواه

بسته داده چیست؟

دسته داده یک فایل دودویی ایستا است که توسط شما ساخته شده است تا یک یا چند سند و/یا عکس آنی پُرسمان را بسته‌بندی کند و از آن می‌توانید پُرسمان‌های نام‌گذاری‌شده را استخراج کنید. همان‌طور که در زیر بحث می‌کنیم، کیت‌های توسعه نرم‌افزار سمت سرور به شما امکان می‌دهند بسته‌ها را بسازید و کیت‌های توسعه نرم‌افزار مشتری روش‌هایی را ارائه می‌دهند که به شما امکان می‌دهند بسته‌ها را در حافظه نهان محلی بار کنید.

پُرسمان‌های نام‌گذاری‌شده یکی از ویژگی‌های بسیار قدرتمند بسته‌ها هستند. پرس‌وجوهای نام‌گذاری‌شده Query اشیایی هستند که می‌توانید از یک بسته استخراج کنید، سپس بلافاصله از آن‌ها استفاده کنید تا داده‌ها را از حافظه پنهان یا از پس‌بک پرس‌وجو کنید، همان‌طور که معمولاً در هر بخشی از برنامه‌تان که با Cloud Firestore صحبت می‌کند انجام می‌دهید.

درحال ساختن بسته‌های داده در سرور

استفاده از Node.js یا Java Admin 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();
      
پایتون
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، چه با فراخوانی Storage API، یا بااستفاده از هر روش دیگری برای واکشی فایل‌های دودویی در شبکه.

پس‌از واکشی، بااستفاده از کیت توسعه نرم‌افزار مشتری Cloud Firestore، برنامه‌تان روش loadBundle را فراخوانی می‌کند که شیء ردیابی تکلیف را برمی‌گرداند، تکمیل آن را می‌توانید به‌همان روشی که وضعیت Promise را پایش می‌کنید پایش کنید. پس‌از تکمیل موفقیت‌آمیز تکلیف بار کردن دسته، محتوای دسته در حافظه نهان محلی دردسترس قرار می‌گیرد.

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
توجه: این محصول در watchOS و App Clip دردسترس نیست.
// 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
توجه: این محصول در watchOS و App Clip دردسترس نیست.
// 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> &){
      // ...
    });
  });
});

توجه داشته باشید که اگر یک پرسمان نام‌گذاری‌شده را از بسته‌ای که کمتر از ۳۰ دقیقه قبل ساخته شده است بارگیری کنید، پس‌از اینکه از آن برای خواندن از پس‌نما به‌جای حافظه پنهان استفاده کردید، فقط برای خواندن پایگاه داده موردنیاز برای به‌روزرسانی اسناد مطابق با آنچه در پس‌نما ذخیره شده است هزینه پرداخت خواهید کرد؛ یعنی فقط برای دلتاها هزینه پرداخت می‌کنید.

بعد چه می‌شود؟