Cloud Functions ile Cloud Firestore'un kapsamını genişletme (2. nesil)

Cloud Functions ile tetiklenen etkinlikleri işlemek için kod dağıtabilirsiniz Cloud Firestore veritabanınızdaki değişikliklere göre değiştirilir. Bu sayede, sunucu tarafını işlevleriyle uygulamanıza entegre edebilirsiniz.

Cloud Functions (2. nesil)

Cloud Run ve Eventarc. Cloud Functions for Firebase (2. nesil) sayesinde daha güçlü altyapı, performans ve ölçeklenebilirlik üzerinde gelişmiş kontrol ve daha fazlası denetiminin arka planında yer alır. 2. nesil hakkında daha fazla bilgi için bkz. Cloud Functions for Firebase (2. nesil). Daha fazlasını görmek için 1. nesil için Cloud Functions ile Cloud Firestore'un kapsamını genişletin.

Cloud Firestore işlev tetikleyicileri

Cloud Functions for Firebase SDK'sı aşağıdaki Cloud Firestore'u dışa aktarır Belirli bir Cloud Firestore'a bağlı işleyiciler oluşturmanızı sağlayan etkinlik tetikleyicileri etkinlikler:

Node.js

Etkinlik Türü Tetikleyici
onDocumentCreated Bir doküman ilk kez yazıldığında tetiklenir.
onDocumentUpdated Zaten bir doküman varsa ve herhangi bir değeri değiştirildiğinde tetiklenir.
onDocumentDeleted Doküman silindiğinde tetiklenir.
onDocumentWritten onDocumentCreated, onDocumentUpdated veya onDocumentDeleted tetiklendiğinde tetiklenir.
onDocumentCreatedWithAuthContext Ek kimlik doğrulama bilgileriyle onDocumentCreated
onDocumentWrittenWithAuthContext Ek kimlik doğrulama bilgileriyle onDocumentWritten
onDocumentDeletedWithAuthContext Ek kimlik doğrulama bilgileriyle onDocumentDeleted
onDocumentUpdatedWithAuthContext Ek kimlik doğrulama bilgileriyle onDocumentUpdated

Python (önizleme)

Etkinlik Türü Tetikleyici
on_document_created Bir doküman ilk kez yazıldığında tetiklenir.
on_document_updated Zaten bir doküman varsa ve herhangi bir değeri değiştirildiğinde tetiklenir.
on_document_deleted Doküman silindiğinde tetiklenir.
on_document_written on_document_created, on_document_updated veya on_document_deleted tetiklendiğinde tetiklenir.
on_document_created_with_auth_context Ek kimlik doğrulama bilgileriyle on_document_created
on_document_updated_with_auth_context Ek kimlik doğrulama bilgileriyle on_document_updated
on_document_deleted_with_auth_context Ek kimlik doğrulama bilgileriyle on_document_deleted
on_document_written_with_auth_context Ek kimlik doğrulama bilgileriyle on_document_written

Yalnızca Cloud Firestore etkinlikleri tetiklenir dikkat edin. Cloud Firestore belgesinde yapılan güncellemeye göre, değişmez (işlemsiz yazma), güncelleme oluşturmaz veya etkinlik yazmaz. Evet belirli alanlara etkinlik eklemek mümkün değildir.

Henüz Firebase için Cloud Functions için etkinleştirilmiş bir projeniz yoksa Cloud Functions for Firebase'i (2. nesil) kullanmaya başlayın Firebase için Cloud Functions projenizi yapılandırıp ayarlayın.

Cloud Firestore tarafından tetiklenen işlevler yazma

İşlev tetikleyicisi tanımlayın

Cloud Firestore tetikleyicisi tanımlamak için belge yolu ve etkinlik türü belirtin:

Node.js

import {
  onDocumentWritten,
  onDocumentCreated,
  onDocumentUpdated,
  onDocumentDeleted,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.myfunction = onDocumentWritten("my-collection/{docId}", (event) => {
   /* ... */ 
});

Python (önizleme)

from firebase_functions.firestore_fn import (
  on_document_created,
  on_document_deleted,
  on_document_updated,
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_created(document="users/{userId}")
def myfunction(event: Event[DocumentSnapshot]) -> None:

Belge yolları, belirli bir dokümana başvurabilir veya joker karakter kalıbı kullanabilirsiniz.

Tek bir doküman belirtin

Belirli bir dokümanda herhangi bir değişiklik için etkinlik tetiklemek isterseniz: aşağıdaki işlevi kullanabilirsiniz.

Node.js

import {
  onDocumentWritten,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.myfunction = onDocumentWritten("users/marie", (event) => {
  // Your code here
});

Python (önizleme)

from firebase_functions.firestore_fn import (
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_written(document="users/marie")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:

Joker karakter kullanarak bir doküman grubu belirtin

Bir doküman grubuna tetikleyici eklemek istiyorsanız, yerine bir {wildcard} kullanın belge kimliği:

Node.js

import {
  onDocumentWritten,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.myfunction = onDocumentWritten("users/{userId}", (event) => {
  // If we set `/users/marie` to {name: "Marie"} then
  // event.params.userId == "marie"
  // ... and ...
  // event.data.after.data() == {name: "Marie"}
});

Python (önizleme)

from firebase_functions.firestore_fn import (
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_written(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # If we set `/users/marie` to {name: "Marie"} then
  event.params["userId"] == "marie"  # True
  # ... and ...
  event.data.after.to_dict() == {"name": "Marie"}  # True

Bu örnekte, users alanındaki herhangi bir dokümanda yer alan herhangi bir alan değiştirildiğinde userId adlı bir joker karakter.

users alanındaki bir dokümanın alt koleksiyonları ve bunlardan birinde bir alan varsa alt koleksiyonlar doküman değiştirildiğinde, userId joker karakteri tetiklenmez.

Joker karakter eşleşmeleri belge yolundan ayıklanır ve event.params içinde depolanır. Uygunsuz toplama işlemi yerine istediğiniz kadar joker karakter tanımlayabilirsiniz veya doküman kimlikleri, örneğin:

Node.js

import {
  onDocumentWritten,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.myfunction = onDocumentWritten("users/{userId}/{messageCollectionId}/{messageId}", (event) => {
    // If we set `/users/marie/incoming_messages/134` to {body: "Hello"} then
    // event.params.userId == "marie";
    // event.params.messageCollectionId == "incoming_messages";
    // event.params.messageId == "134";
    // ... and ...
    // event.data.after.data() == {body: "Hello"}
});

Python (önizleme)

from firebase_functions.firestore_fn import (
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_written(document="users/{userId}/{messageCollectionId}/{messageId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # If we set `/users/marie/incoming_messages/134` to {body: "Hello"} then
  event.params["userId"] == "marie"  # True
  event.params["messageCollectionId"] == "incoming_messages"  # True
  event.params["messageId"] == "134"  # True
  # ... and ...
  event.data.after.to_dict() == {"body": "Hello"}

Joker karakter kullansanız bile tetikleyiciniz her zaman bir dokümana işaret etmelidir. Örneğin, {messageCollectionId} nedeniyle users/{userId}/{messageCollectionId} geçerli değil bir koleksiyondur. Ancak, users/{userId}/{messageCollectionId}/{messageId} şudur: {messageId} her zaman bir dokümana işaret edeceği için geçerlidir.

Etkinlik Tetikleyicileri

Yeni doküman oluşturulduğunda bir işlevi tetikle

Koleksiyonda yeni bir doküman oluşturulduğunda bir işlevin tetiklenmesini sağlayabilirsiniz. Bu örnek işlev her yeni kullanıcı profili eklendiğinde tetiklenir:

Node.js

import {
  onDocumentCreated,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.createuser = onDocumentCreated("users/{userId}", (event) => {
    // Get an object representing the document
    // e.g. {'name': 'Marie', 'age': 66}
    const snapshot = event.data;
    if (!snapshot) {
        console.log("No data associated with the event");
        return;
    }
    const data = snapshot.data();

    // access a particular field as you would any JS property
    const name = data.name;

    // perform more operations ...
});

Ek kimlik doğrulama bilgileri için onDocumentCreatedWithAuthContext kullanın.

Python (önizleme)

from firebase_functions.firestore_fn import (
  on_document_created,
  Event,
  DocumentSnapshot,
)

@on_document_created(document="users/{userId}")
def myfunction(event: Event[DocumentSnapshot]) -> None:
  # Get a dictionary representing the document
  # e.g. {'name': 'Marie', 'age': 66}
  new_value = event.data.to_dict()

  # Access a particular field as you would any dictionary
  name = new_value["name"]

  # Perform more operations ...

Doküman güncellendiğinde bir işlevi tetikleyin

Ayrıca, bir doküman güncellendiğinde de etkinleşecek bir işlev tetikleyebilirsiniz. Bu örnek işlev, bir kullanıcı profilini değiştirirse tetiklenir:

Node.js

import {
  onDocumentUpdated,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.updateuser = onDocumentUpdated("users/{userId}", (event) => {
    // Get an object representing the document
    // e.g. {'name': 'Marie', 'age': 66}
    const newValue = event.data.after.data();

    // access a particular field as you would any JS property
    const name = newValue.name;

    // perform more operations ...
});

Ek kimlik doğrulama bilgileri için onDocumentUpdatedWithAuthContext kullanın.

Python (önizleme)

from firebase_functions.firestore_fn import (
  on_document_updated,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_updated(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # Get a dictionary representing the document
  # e.g. {'name': 'Marie', 'age': 66}
  new_value = event.data.after.to_dict()

  # Access a particular field as you would any dictionary
  name = new_value["name"]

  # Perform more operations ...

Doküman silindiğinde bir işlevi tetikle

Doküman silindiğinde de bir işlevi tetikleyebilirsiniz. Bu örnek işlevi, kullanıcı, kullanıcı profilini sildiğinde etkinleşir:

Node.js

import {
  onDocumentDeleted,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.deleteuser = onDocumentDeleted("users/{userId}", (event) => {
    // Get an object representing the document
    // e.g. {'name': 'Marie', 'age': 66}
    const snap =  event.data;
    const data =  snap.data();

    // perform more operations ...
});

Ek kimlik doğrulama bilgileri için onDocumentDeletedWithAuthContext kullanın.

Python (önizleme)

from firebase_functions.firestore_fn import (
  on_document_deleted,
  Event,
  DocumentSnapshot,
)

@on_document_deleted(document="users/{userId}")
def myfunction(event: Event[DocumentSnapshot|None]) -> None:
  # Perform more operations ...

Dokümanda yapılan tüm değişikliklerde bir işlevi tetikleme

Tetiklenen etkinliğin türü sizin için önemli değilse tüm etkinlikleri dinleyebilirsiniz "yazılan belge" kullanılarak Cloud Firestore dokümanında yapılan değişiklikler etkinlik tetikleyici olur. Bu örnek işlev, bir kullanıcı oluşturulduğunda, güncellendiğinde veya silindiğinde etkinleşir:

Node.js

import {
  onDocumentWritten,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.modifyuser = onDocumentWritten("users/{userId}", (event) => {
    // Get an object with the current document values.
    // If the document does not exist, it was deleted
    const document =  event.data.after.data();

    // Get an object with the previous document values
    const previousValues =  event.data.before.data();

    // perform more operations ...
});

Ek kimlik doğrulama bilgileri için onDocumentWrittenWithAuthContext kullanın.

Python (önizleme)

from firebase_functions.firestore_fn import (
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_written(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot | None]]) -> None:
  # Get an object with the current document values.
  # If the document does not exist, it was deleted.
  document = (event.data.after.to_dict()
              if event.data.after is not None else None)

  # Get an object with the previous document values.
  # If the document does not exist, it was newly created.
  previous_values = (event.data.before.to_dict()
                     if event.data.before is not None else None)

  # Perform more operations ...

Verileri Okuma ve Yazma

Bir işlev tetiklendiğinde, her bir işlevle alakalı verilerin bir unutmayın. Bu anlık görüntüyü, yazınızı okumak veya dokümana yazmak için kullanabilirsiniz etkinliği tetikleyebilir veya Firebase Admin SDK'sını kullanarak diğer bölümlere erişebilir yeniden değerlendirmenizi sağlar.

Etkinlik Verileri

Verileri Okuma

Bir fonksiyon tetiklendiğinde, düzgün çalışan bir dokümandan veya güncellemeden önce verileri alın. Önceki verileri almak için event.data.before, güncellemeden önceki dokümanın anlık görüntüsünü içerir. Benzer şekilde, event.data.after etiketinden sonraki güncelleyin.

Node.js

exports.updateuser2 = onDocumentUpdated("users/{userId}", (event) => {
    // Get an object with the current document values.
    // If the document does not exist, it was deleted
    const newValues =  event.data.after.data();

    // Get an object with the previous document values
    const previousValues =  event.data.before.data();
});

Python (önizleme)

@on_document_updated(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # Get an object with the current document values.
  new_value = event.data.after.to_dict()

  # Get an object with the previous document values.
  prev_value = event.data.before.to_dict()

Mülklere, diğer herhangi bir nesnede olduğu gibi erişebilirsiniz. Alternatif olarak belirli alanlara erişmek için get işlevini kullanabilir:

Node.js

// Fetch data using standard accessors
const age = event.data.after.data().age;
const name = event.data.after.data()['name'];

// Fetch data using built in accessor
const experience = event.data.after.data.get('experience');

Python (önizleme)

# Get the value of a single document field.
age = event.data.after.get("age")

# Convert the document to a dictionary.
age = event.data.after.to_dict()["age"]

Veri Yazma

Her işlev çağrısı, Cloud Firestore veritabanı. Bu dokümana şuradan erişebilirsiniz: işlevinize döndürülen anlık görüntü gerekir.

Belge referansı update(), set() ve remove() gibi yöntemler içeriyor Böylece, işlevi tetikleyen dokümanı değiştirebilirsiniz.

Node.js

import { onDocumentUpdated } from "firebase-functions/v2/firestore";

exports.countnamechanges = onDocumentUpdated('users/{userId}', (event) => {
  // Retrieve the current and previous value
  const data = event.data.after.data();
  const previousData = event.data.before.data();

  // We'll only update if the name has changed.
  // This is crucial to prevent infinite loops.
  if (data.name == previousData.name) {
    return null;
  }

  // Retrieve the current count of name changes
  let count = data.name_change_count;
  if (!count) {
    count = 0;
  }

  // Then return a promise of a set operation to update the count
  return data.after.ref.set({
    name_change_count: count + 1
  }, {merge: true});

});

Python (önizleme)

@on_document_updated(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # Get the current and previous document values.
  new_value = event.data.after
  prev_value = event.data.before

  # We'll only update if the name has changed.
  # This is crucial to prevent infinite loops.
  if new_value.get("name") == prev_value.get("name"):
      return

  # Retrieve the current count of name changes
  count = new_value.to_dict().get("name_change_count", 0)

  # Update the count
  new_value.reference.update({"name_change_count": count + 1})

Kullanıcı kimlik doğrulama bilgilerine erişme

Aşağıdaki etkinlik türlerinden birini kullanıyorsanız Etkinliği tetikleyen ana hesapla ilgili kullanıcı kimlik doğrulama bilgileri Bu bilgiler, temel etkinlikte döndürülen bilgilere ek olarak sunulur.

Node.js

  • onDocumentCreatedWithAuthContext
  • onDocumentWrittenWithAuthContext
  • onDocumentDeletedWithAuthContext
  • onDocumentUpdatedWithAuthContext

Python (önizleme)

  • on_document_created_with_auth_context
  • on_document_updated_with_auth_context
  • on_document_deleted_with_auth_context
  • on_document_written_with_auth_context

Kimlik doğrulama bağlamında mevcut olan veriler hakkında bilgi için bkz. Kimlik Doğrulama Bağlamı. Aşağıdaki örnekte, kimlik doğrulama bilgilerinin nasıl alınacağı gösterilmektedir:

Node.js

import { onDocumentWrittenWithAuthContext } from "firebase-functions/v2/firestore"

exports.syncUser = onDocumentWrittenWithAuthContext("users/{userId}", (event) => {
    const snapshot = event.data.after;
    if (!snapshot) {
        console.log("No data associated with the event");
        return;
    }
    const data = snapshot.data();

    // retrieve auth context from event
    const { authType, authId } = event;

    let verified = false;
    if (authType === "system") {
      // system-generated users are automatically verified
      verified = true;
    } else if (authType === "unknown" || authType === "unauthenticated") {
      // admin users from a specific domain are verified
      if (authId.endsWith("@example.com")) {
        verified = true;
      }
    }

    return data.after.ref.set({
        created_by: authId,
        verified,
    }, {merge: true}); 
}); 

Python (önizleme)

@on_document_updated_with_auth_context(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:

  # Get the current and previous document values.
  new_value = event.data.after
  prev_value = event.data.before

  # Get the auth context from the event
  user_auth_type = event.auth_type
  user_auth_id = event.auth_id

Tetikleyici etkinliğin dışındaki veriler

Cloud Functions, güvenilir bir ortamda yürütülür. Bunlar: bir hizmet hesabı olarak yetkilendirdiğinize göre hem okuma hem de Firebase Admin SDK'yı kullanarak yazar:

Node.js

const { initializeApp } = require('firebase-admin/app');
const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');

initializeApp();
const db = getFirestore();

exports.writetofirestore = onDocumentWritten("some/doc", (event) => {
    db.doc('some/otherdoc').set({ ... });
  });

  exports.writetofirestore = onDocumentWritten('users/{userId}', (event) => {
    db.doc('some/otherdoc').set({
      // Update otherdoc
    });
  });

Python (önizleme)

from firebase_admin import firestore, initialize_app
import google.cloud.firestore

initialize_app()

@on_document_written(document="some/doc")
def myfunction(event: Event[Change[DocumentSnapshot | None]]) -> None:
  firestore_client: google.cloud.firestore.Client = firestore.client()
  firestore_client.document("another/doc").set({
      # ...
  })

Sınırlamalar

Cloud Functions için Cloud Firestore tetikleyicileriyle ilgili aşağıdaki sınırlamaları göz önünde bulundurun:

  • Cloud Functions (1. nesil) için mevcut bir "(varsayılan)" ön koşulu bulunur veritabanını Firestore yerel modunda kullanır. İçermiyor: Cloud Firestore adlı veritabanlarını veya Datastore modunu desteklemelidir. Lütfen Cloud Functions'ı kullanın (2. nesil) teknolojisinden yararlanabilirsiniz.
  • Sipariş verme garantisi verilmez. Hızlı değişiklikler beklenmedik bir durum var.
  • Etkinlikler en az bir kez teslim edilir ancak tek bir etkinlik sonucunda birden çok işlev çağrısında bulunur. Şuna bağlı olarak kullanmaktan kaçının: bilgisayar korsanlığı içeren bir oyun ihtiyatlı işlevler hakkında daha fazla bilgi edinin.
  • Datastore modunda Cloud Firestore Cloud Functions (2. nesil) gerektirir. Cloud Functions (1. nesil) Datastore modunu desteklemeli.
  • Tetikleyici, tek bir veritabanıyla ilişkilendirilir. Birden çok veritabanıyla eşleşen bir tetikleyici oluşturamazsınız.
  • Veritabanının silinmesi, o veritabanına ait tetikleyicilerin otomatik olarak silinmesine neden olmaz. İlgili içeriği oluşturmak için kullanılan tetikleyici etkinlikleri yayınlamayı durdurur ancak siz tetikleyici silene kadar var olmaya devam eder.
  • Eşleşen bir etkinlik maksimum istek boyutunu aşarsa etkinliği Cloud Functions'a (1. nesil) teslim edilemeyebilir.
    • İstek boyutu nedeniyle yayınlanmayan etkinlikler platform günlüklerine kaydedilir ve projenin günlük kullanımına dahil edilir.
    • Bu günlükleri, Günlük Gezgini'nde "Etkinlik hedefine teslim edilemiyor" mesajıyla bulabilirsiniz 1. nesil sınırı aşması nedeniyle bulut işlevi..." / error önem derecesi. İşlev adını functionName alanının altında bulabilirsiniz. Eğer receiveTimestamp alanına şu andan itibaren bir saat daha var: söz konusu dokümanı bir sorguyla okuyarak gerçek etkinlik içeriğini ve zaman damgasından önceki ve sonraki anlık görüntülere yer verir.
    • Bu sıklığı önlemek için şunları yapabilirsiniz:
      • Cloud Functions'ı (2. nesil) taşıyın ve yükseltin
      • Dokümanın boyutunu küçült
      • İlgili Cloud Functions işlevlerini silin
    • Hariç tutma özelliğini kullanarak günlük kaydını kapatabilirsiniz. ancak rahatsız edici etkinliklerin yine de teslim edilmeyeceğini unutmayın.