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

Cloud Functions ile, MongoDB uyumlu Cloud Firestore veritabanınızdaki değişiklikler tarafından tetiklenen etkinlikleri işlemek için kod dağıtabilirsiniz. Bu sayede, kendi sunucularınızı çalıştırmadan uygulamanıza sunucu tarafı işlevselliği ekleyebilirsiniz.

Cloud Functions (2. nesil)

Cloud Run ve Eventarc tarafından desteklenen Cloud Functions for Firebase (2. nesil), daha güçlü bir altyapı, performans ve ölçeklenebilirlik üzerinde gelişmiş kontrol ve çalışma zamanı işlevleri üzerinde daha fazla kontrol sağlar. 2. nesil hakkında daha fazla bilgi için Cloud Functions for Firebase (2. nesil) başlıklı makaleyi inceleyin.

MongoDB uyumlu Cloud Firestore işlevi tetikleyicileri

Cloud Functions for Firebase SDK, MongoDB uyumlu Cloud Firestore ile ilgili belirli olaylara bağlı işleyiciler oluşturmanıza olanak tanımak için aşağıdaki MongoDB uyumlu Cloud Firestore olay tetikleyicilerini dışa aktarır:

Node.js

Etkinlik Türü Tetikleyici
onDocumentCreated Bir dokümana ilk kez yazıldığında tetiklenir.
onDocumentUpdated Halihazırda mevcut olan bir dokümanda herhangi bir değer değiştirildiğinde tetiklenir.
onDocumentDeleted Bir doküman silindiğinde tetiklenir.
onDocumentWritten onDocumentCreated, onDocumentUpdated veya onDocumentDeleted tetiklendiğinde tetiklenir.
onDocumentCreatedWithAuthContext onDocumentCreated ek kimlik doğrulama bilgileriyle
onDocumentWrittenWithAuthContext onDocumentWritten ek kimlik doğrulama bilgileriyle
onDocumentDeletedWithAuthContext onDocumentDeleted ek kimlik doğrulama bilgileriyle
onDocumentUpdatedWithAuthContext onDocumentUpdated ek kimlik doğrulama bilgileriyle

Python

Etkinlik Türü Tetikleyici
on_document_created Bir dokümana ilk kez yazıldığında tetiklenir.
on_document_updated Halihazırda mevcut olan bir dokümanda herhangi bir değer değiştirildiğinde tetiklenir.
on_document_deleted Bir 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 on_document_created ek kimlik doğrulama bilgileriyle
on_document_updated_with_auth_context on_document_updated ek kimlik doğrulama bilgileriyle
on_document_deleted_with_auth_context on_document_deleted ek kimlik doğrulama bilgileriyle
on_document_written_with_auth_context on_document_written ek kimlik doğrulama bilgileriyle

MongoDB uyumlu Cloud Firestore etkinlikleri yalnızca doküman değişikliklerinde tetiklenir. Verilerin değişmediği (işlem yapmayan yazma) MongoDB uyumlu bir Cloud Firestore dokümanının güncellenmesi, güncelleme veya yazma etkinliği oluşturmaz. Belirli alanlara etkinlik eklemek mümkün değildir.

Henüz Cloud Functions for Firebase için etkinleştirilmiş bir projeniz yoksa Cloud Functions for Firebase projenizi yapılandırmak ve ayarlamak için Cloud Functions for Firebase (2. nesil) ile kullanmaya başlama başlıklı makaleyi inceleyin.

MongoDB uyumlu Cloud Firestore ile tetiklenen işlevler yazma

İşlev tetikleyicisi tanımlama

MongoDB uyumlu bir Cloud Firestore tetikleyicisi tanımlamak için bir doküman yolu ve etkinlik türü belirtin:

Node.js

const {
  onDocumentWritten,
  onDocumentCreated,
  onDocumentUpdated,
  onDocumentDeleted,
  Change,
  FirestoreEvent
} = require('firebase-functions/v2/firestore');

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

Python

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:

Doküman yolları, belirli bir dokümana veya joker karakter desenine başvurabilir.

Tek bir doküman belirtme

Belirli bir dokümanda herhangi bir değişiklik yapıldığında etkinlik tetiklemek istiyorsanız aşağıdaki işlevi kullanabilirsiniz.

Node.js

const {
  onDocumentWritten,
  Change,
  FirestoreEvent
} = require('firebase-functions/v2/firestore');

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

Python

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 karakterler kullanarak bir grup belge belirtme

Belirli bir koleksiyondaki tüm belgeler gibi bir belge grubuna tetikleyici eklemek istiyorsanız belge kimliği yerine {wildcard} kullanın:

Node.js

const {
  onDocumentWritten,
  Change,
  FirestoreEvent
} = require('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

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 içindeki herhangi bir dokümanda yer alan herhangi bir alan değiştirildiğinde userId adlı bir joker karakterle eşleşir.

Joker karakter eşleşmeleri, belge yolundan ayıklanır ve event.params içinde depolanır. Joker karakter kullanıyor olsanız bile tetikleyiciniz her zaman bir dokümanı işaret etmelidir.

Etkinlik tetikleyicileri

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

Bir koleksiyonda yeni bir doküman oluşturulduğunda tetiklenecek bir işlev oluşturabilirsiniz. Bu örnek işlev, her yeni kullanıcı profili eklendiğinde tetiklenir:

Node.js

const {
  onDocumentCreated,
  Change,
  FirestoreEvent
} = require('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

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 ...

Bir doküman güncellendiğinde işlev tetikleme

Ayrıca, bir doküman güncellendiğinde tetiklenecek bir işlev de ayarlayabilirsiniz. Bu örnek işlev, kullanıcı profilini değiştirdiğinde tetiklenir:

Node.js

const {
  onDocumentUpdated,
  Change,
  FirestoreEvent
} = require('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

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 ...

Bir doküman silindiğinde işlev tetikleme

Bir belge silindiğinde de işlev tetikleyebilirsiniz. Bu örnek işlev, kullanıcı kendi kullanıcı profilini sildiğinde tetiklenir:

Node.js

const {
  onDocumentDeleted,
  Change,
  FirestoreEvent
} = require('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

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 ...

Bir dokümanda yapılan tüm değişiklikler için bir işlevi tetikleme

Tetiklenen etkinlik türüyle ilgilenmiyorsanız "document written" etkinlik tetikleyicisini kullanarak MongoDB uyumlu bir Cloud Firestore dokümanındaki tüm değişiklikleri dinleyebilirsiniz. Bu örnek işlev, bir kullanıcı oluşturulursa, güncellenirse veya silinirse tetiklenir:

Node.js

const {
  onDocumentWritten,
  Change,
  FirestoreEvent
} = require('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

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, etkinlikle ilgili verilerin anlık görüntüsünü sağlar. Bu anlık görüntüyü, etkinliği tetikleyen dokümandan okumak veya bu dokümana yazmak için kullanabilir ya da Firebase Admin SDK'yı kullanarak veritabanınızın diğer bölümlerine erişebilirsiniz.

Etkinlik Verileri

Verileri Okuma

Bir işlev tetiklendiğinde, güncellenen bir dokümandaki verileri veya güncellemeden önceki verileri almak isteyebilirsiniz. Güncellemeden önceki doküman anlık görüntüsünü içeren event.data.before kullanarak önceki verilere ulaşabilirsiniz. Benzer şekilde, event.data.after, güncellemeden sonraki doküman anlık görüntüsünün durumunu içerir.

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

@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()

Özelliklere diğer nesnelerde olduğu gibi erişebilirsiniz. Alternatif olarak, belirli alanlara erişmek için get işlevini kullanabilirsiniz:

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

# 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ı, MongoDB uyumlu Cloud Firestore veritabanınızdaki belirli bir belgeyle ilişkilendirilir. Bu dokümana, işlevinize döndürülen anlık görüntüden erişebilirsiniz.

Doküman referansı, işlevi tetikleyen dokümanı değiştirebilmeniz için update(), set() ve remove() gibi yöntemler içerir.

Node.js

const {onDocumentUpdated} = require('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 event.data.after.ref.set({
    name_change_count: count + 1
  }, {merge: true});

});

Python

@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 asıl kullanıcıyla ilgili kullanıcı kimlik doğrulama bilgilerine erişebilirsiniz. Bu bilgiler, temel etkinlikte döndürülen bilgilere ek olarak sağlanır.

Node.js

  • onDocumentCreatedWithAuthContext
  • onDocumentWrittenWithAuthContext
  • onDocumentDeletedWithAuthContext
  • onDocumentUpdatedWithAuthContext

Python

  • 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 kullanılabilen veriler hakkında bilgi için Auth Context (Kimlik Doğrulama Bağlamı) başlıklı makaleyi inceleyin. Aşağıdaki örnekte, kimlik doğrulama bilgilerinin nasıl alınacağı gösterilmektedir:

Node.js

const {onDocumentWrittenWithAuthContext} = require('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

@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 etkinlik dışındaki veriler

Cloud Functions güvenilir bir ortamda yürütülür. Bu hesaplar, projenizde hizmet hesabı olarak yetkilendirilir ve Firebase Admin SDK'sını kullanarak okuma ve yazma işlemleri gerçekleştirebilirsiniz:

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

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

  • Sipariş verme garantisi yoktur. Hızlı değişiklikler, işlev çağrılarının beklenmedik bir sırada tetiklenmesine neden olabilir.
  • Etkinlikler en az bir kez teslim edilir ancak tek bir etkinlik birden fazla işlev çağrısına neden olabilir. Tam olarak bir kez mekanizmalarına bağlı kalmaktan kaçının ve idempotent işlevler yazın.
  • Tetikleyici tek bir veritabanıyla ilişkilendirilir. Birden fazla veritabanıyla eşleşen bir tetikleyici oluşturamazsınız.
  • Bir veritabanının silinmesi, o veritabanıyla ilgili tetikleyicileri otomatik olarak silmez. Tetikleyici, etkinlikleri yayınlamayı durdurur ancak siz tetikleyiciyi silene kadar varlığını sürdürür.