Firestore 트리거(2세대)

Firestore 데이터베이스의 이벤트에 의해 트리거되도록 Cloud Functions를 구성할 수 있습니다. 함수가 트리거되면 Firestore API 및 클라이언트 라이브러리를 통해 이러한 이벤트에 대한 응답으로 Firestore 데이터베이스를 읽고 업데이트할 수 있습니다.

일반적인 수명 주기에서 Firestore 함수는 다음을 수행합니다.

  1. 특정 문서가 변경되기를 기다립니다.

  2. 이벤트가 발생하면 트리거되어 작업을 수행합니다.

  3. 영향을 받는 문서의 스냅샷이 있는 데이터 객체를 수신합니다. write 또는 update 이벤트의 경우 데이터 객체에는 이벤트 트리거 전후의 문서 상태를 나타내는 스냅샷이 포함됩니다.

이벤트 유형

Firestore는 create, update, delete, write 이벤트를 지원합니다. write 이벤트는 문서에 대한 모든 수정사항을 포함합니다.

이벤트 유형 트리거
google.cloud.firestore.document.v1.created(기본) 문서를 처음으로 기록할 때 트리거됩니다.
google.cloud.firestore.document.v1.updated 이미 존재하는 문서에서 값이 변경되었을 때 트리거됩니다.
google.cloud.firestore.document.v1.deleted 데이터가 있는 문서가 삭제되면 트리거됩니다.
google.cloud.firestore.document.v1.written 문서가 생성, 업데이트 또는 삭제되면 트리거됩니다.

와일드 카드는 다음과 같이 중괄호를 사용하여 트리거에 작성됩니다. "projects/YOUR_PROJECT_ID/databases/(default)/documents/collection/{document_wildcard}"

문서 경로 지정

함수를 트리거하려면 리슨할 문서 경로를 지정합니다. 문서 경로가 함수와 동일한 Google Cloud 프로젝트에 있어야 합니다.

다음은 유효한 문서 경로의 몇 가지 예시입니다.

  • users/marie: 유효한 트리거입니다. 단일 문서 /users/marie를 모니터링합니다.

  • users/{username}: 유효한 트리거입니다. 모든 사용자 문서를 모니터링합니다. 와일드 카드를 사용하면 컬렉션의 모든 문서를 모니터링할 수 있습니다.

  • users/{username}/addresses: 트리거가 잘못되었습니다. 문서가 아닌 하위 컬렉션 addresses를 나타냅니다.

  • users/{username}/addresses/home: 유효한 트리거입니다. 모든 사용자에 대한 집 주소 문서를 모니터링합니다.

  • users/{username}/addresses/{addressId}: 유효한 트리거입니다. 모든 주소 문서를 모니터링합니다.

  • users/{user=**}: 유효한 트리거입니다. 모든 사용자 문서와 /users/userID/address/home 또는 /users/userID/phone/work 등 각 사용자 문서에 포함된 하위 컬렉션의 문서를 모니터링합니다.

와일드 카드 및 매개변수

모니터링할 특정 문서를 알 수 없는 경우에는 문서 ID 대신 {wildcard}를 사용합니다.

  • users/{username}은 모든 사용자 문서에 대한 변경을 리슨합니다.

이 예시에서 users의 문서에서 필드가 변경되면 필드는 {username}라는 와일드 카드와 일치합니다.

users의 문서에 하위 컬렉션이 있고, 이 하위 컬렉션 문서 중 하나에서 필드가 변경되면 {username} 와일드 카드가 트리거되지 않습니다. 하위 컬렉션의 이벤트에도 응답하려는 경우 다중 세그먼트 와일드 카드 {username=**}을 사용합니다.

와일드 카드 일치는 문서 경로에서 추출됩니다. 원하는 만큼 와일드 카드를 정의하여 명시적 컬렉션 또는 문서 ID를 대체할 수 있습니다. {username=**}과 같이 최대 한 개의 다중 세그먼트 와일드 카드를 사용할 수 있습니다.

이벤트 구조

이 트리거는 다음과 유사한 이벤트로 함수를 호출합니다.

{
    "oldValue": { // Update and Delete operations only
        A Document object containing a pre-operation document snapshot
    },
    "updateMask": { // Update operations only
        A DocumentMask object that lists changed fields.
    },
    "value": {
        // A Document object containing a post-operation document snapshot
    }
}

Document 객체에는 Value 객체가 하나 이상 포함됩니다. 유형 참조는 Value 문서를 참조하세요. 특히 Go와 같은 입력 언어를 사용하여 함수를 작성하는 경우에 유용합니다.

Firestore 데이터베이스 설정

이 문서의 샘플을 테스트하려면 Firestore 데이터베이스가 필요합니다. 함수를 배포하기 전에 올바른 위치에 있어야 합니다. 아직 Firestore 데이터베이스가 없으면 다음과 같이 데이터베이스를 만듭니다.

  1. Firestore 데이터 페이지로 이동합니다.

  2. 기본 모드 선택을 클릭합니다.

  3. 데이터베이스가 상주할 리전(위치)을 선택합니다. 이 선택은 되돌릴 수 없습니다.

  4. 데이터베이스 만들기를 클릭합니다.

Firestore 데이터 모델은 문서가 포함된 컬렉션으로 구성됩니다. 각 문서에는 키-값 쌍이 들어 있습니다.

이 튜토리얼에서 만드는 함수는 지정된 컬렉션 내에서 문서를 변경할 때 트리거됩니다.

예시 1: Hello Firestore 함수

다음 샘플 Cloud 함수는 트리거하는 Firestore 이벤트의 필드를 출력합니다.

Node.js

protobufjs를 사용하여 이벤트 데이터를 디코딩합니다. 소스에 google.events.cloud.firestore.v1 data.proto를 포함합니다.

/**
 * Cloud Event Function triggered by a change to a Firestore document.
 */
const functions = require('@google-cloud/functions-framework');
const protobuf = require('protobufjs');

functions.cloudEvent('helloFirestore', async cloudEvent => {
  console.log(`Function triggered by event on: ${cloudEvent.source}`);
  console.log(`Event type: ${cloudEvent.type}`);

  console.log('Loading protos...');
  const root = await protobuf.load('data.proto');
  const DocumentEventData = root.lookupType(
    'google.events.cloud.firestore.v1.DocumentEventData'
  );

  console.log('Decoding data...');
  const firestoreReceived = DocumentEventData.decode(cloudEvent.data);

  console.log('\nOld value:');
  console.log(JSON.stringify(firestoreReceived.oldValue, null, 2));

  console.log('\nNew value:');
  console.log(JSON.stringify(firestoreReceived.value, null, 2));
});

Python

from cloudevents.http import CloudEvent
import functions_framework
from google.events.cloud import firestore

@functions_framework.cloud_event
def hello_firestore(cloud_event: CloudEvent) -> None:
    """Triggers by a change to a Firestore document.

    Args:
        cloud_event: cloud event with information on the firestore event trigger
    """
    firestore_payload = firestore.DocumentEventData()
    firestore_payload._pb.ParseFromString(cloud_event.data)

    print(f"Function triggered by change to: {cloud_event['source']}")

    print("\nOld value:")
    print(firestore_payload.old_value)

    print("\nNew value:")
    print(firestore_payload.value)

Go


// Package hellofirestore contains a Cloud Event Function triggered by a Cloud Firestore event.
package hellofirestore

import (
	"context"
	"fmt"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
	"github.com/googleapis/google-cloudevents-go/cloud/firestoredata"
	"google.golang.org/protobuf/proto"
)

func init() {
	functions.CloudEvent("helloFirestore", HelloFirestore)
}

// HelloFirestore is triggered by a change to a Firestore document.
func HelloFirestore(ctx context.Context, event event.Event) error {
	var data firestoredata.DocumentEventData
	if err := proto.Unmarshal(event.Data(), &data); err != nil {
		return fmt.Errorf("proto.Unmarshal: %w", err)
	}

	fmt.Printf("Function triggered by change to: %v\n", event.Source())
	fmt.Printf("Old value: %+v\n", data.GetOldValue())
	fmt.Printf("New value: %+v\n", data.GetValue())
	return nil
}

Java

import com.google.cloud.functions.CloudEventsFunction;
import com.google.events.cloud.firestore.v1.DocumentEventData;
import com.google.protobuf.InvalidProtocolBufferException;
import io.cloudevents.CloudEvent;
import java.util.logging.Logger;

public class FirebaseFirestore implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(FirebaseFirestore.class.getName());

  @Override
  public void accept(CloudEvent event) throws InvalidProtocolBufferException {
    DocumentEventData firestorEventData = DocumentEventData.parseFrom(event.getData().toBytes());

    logger.info("Function triggered by event on: " + event.getSource());
    logger.info("Event type: " + event.getType());

    logger.info("Old value:");
    logger.info(firestorEventData.getOldValue().toString());

    logger.info("New value:");
    logger.info(firestorEventData.getValue().toString());
  }
}

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.Firestore.V1;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace FirebaseFirestore;

public class Function : ICloudEventFunction<DocumentEventData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, DocumentEventData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Function triggered by event on {subject}", cloudEvent.Subject);
        _logger.LogInformation("Event type: {type}", cloudEvent.Type);
        MaybeLogDocument("Old value", data.OldValue);
        MaybeLogDocument("New value", data.Value);

        // In this example, we don't need to perform any asynchronous operations, so the
        // method doesn't need to be declared async.
        return Task.CompletedTask;
    }

    /// <summary>
    /// Logs the names and values of the fields in a document in a very simplistic way.
    /// </summary>
    private void MaybeLogDocument(string message, Document document)
    {
        if (document is null)
        {
            return;
        }

        // ConvertFields converts the Firestore representation into a .NET-friendly
        // representation.
        IReadOnlyDictionary<string, object> fields = document.ConvertFields();
        var fieldNamesAndTypes = fields
            .OrderBy(pair => pair.Key)
            .Select(pair => $"{pair.Key}: {pair.Value}");
        _logger.LogInformation(message + ": {fields}", string.Join(", ", fieldNamesAndTypes));
    }
}

Hello Firestore 함수 배포

  1. 아직 설정하지 않았다면 Firestore 데이터베이스를 설정합니다.

  2. Firestore 트리거를 사용하여 Hello Firestore 함수를 배포하려면 샘플 코드(또는 자바의 경우 pom.xml 파일)가 포함된 디렉터리에서 다음 명령어를 실행합니다.

    gcloud functions deploy FUNCTION_NAME \
    --gen2 \
    --runtime=RUNTIME \
    --region=REGION \
    --trigger-location=TRIGGER REGION \
    --source=. \
    --entry-point=ENTRY_POINT \
    --trigger-event-filters=type=google.cloud.firestore.document.v1.written \
    --trigger-event-filters=database='(default)' \
    --trigger-event-filters-path-pattern=document='users/{username}'
    

    다음을 바꿉니다.

    • FUNCTION_NAME: 배포된 함수의 이름입니다.
    • RUNTIME: 함수에서 사용하는 언어 런타임입니다.
    • REGION: 함수를 배포할 리전입니다.
    • TRIGGER_REGION: 트리거의 위치이며 Firestore 데이터베이스 리전과 동일해야 합니다.
    • ENTRY_POINT: 소스 코드에 있는 함수의 진입점입니다. 이는 함수가 실행될 때 실행되는 코드입니다.

    다른 필드는 다음과 같이 그대로 사용합니다.

    • --trigger-event-filters=type=google.cloud.firestore.document.v1.writtengoogle.cloud.firestore.document.v1.written 이벤트 유형에 따라 문서가 생성, 업데이트 또는 삭제될 때 함수가 트리거되도록 지정합니다.
    • --trigger-event-filters=database='(default)'는 Firebase 데이터베이스를 지정합니다. 기본 데이터베이스 이름으로는 (default)를 사용합니다.
    • --trigger-event-filters-path-pattern=document='users/{username}'은 관련 변경사항을 모니터링해야 하는 문서의 경로 패턴을 제공합니다. 이 경로 패턴은 users 컬렉션의 모든 문서를 모니터링해야 함을 나타냅니다. 자세한 내용은 경로 패턴 이해를 참조하세요.

Hello Firestore 함수 테스트

Hello Firestore 함수를 테스트하려면 Firestore 데이터베이스users 컬렉션을 설정합니다.

  1. Firestore 데이터 페이지에서 컬렉션 시작을 클릭합니다.

  2. 컬렉션 ID로 users를 지정합니다.

  3. 컬렉션의 첫 번째 문서 추가를 시작하려면 첫 번째 문서 추가에서 자동 생성된 문서 ID를 수락합니다.

  4. 문서에 대한 필드를 하나 이상 추가하고 이름과 값을 지정합니다. 이 예시에서 이름은 'username'이며 값은 'rowan'입니다.

    Firestore 컬렉션 만들기를 보여주는 스크린샷

  5. 완료했으면 저장을 클릭합니다.

    이 작업은 새 문서를 만들어 함수를 트리거합니다.

  6. 함수가 트리거되었는지 확인하려면 Google Cloud Console Cloud Functions 개요 페이지에서 함수의 링크된 이름을 클릭하여 함수 세부정보 페이지를 엽니다.

  7. 로그 탭을 열고 다음 문자열을 찾습니다.

Function triggered by change to: //firestore.googleapis.com/projects/your-project-id/databases/(default)'

예시 2: 대문자로 변환 함수

이 예시에서는 사용자가 추가한 값을 검색하고 해당 위치의 문자열을 대문자로 변환한 후 해당 값을 대문자 문자열로 바꿉니다.

Node.js

protobufjs를 사용하여 이벤트 데이터를 디코딩합니다. 소스에 google.events.cloud.firestore.v1 data.proto를 포함합니다.

const functions = require('@google-cloud/functions-framework');
const Firestore = require('@google-cloud/firestore');
const protobuf = require('protobufjs');

const firestore = new Firestore({
  projectId: process.env.GOOGLE_CLOUD_PROJECT,
});

// Converts strings added to /messages/{pushId}/original to uppercase
functions.cloudEvent('makeUpperCase', async cloudEvent => {
  console.log('Loading protos...');
  const root = await protobuf.load('data.proto');
  const DocumentEventData = root.lookupType(
    'google.events.cloud.firestore.v1.DocumentEventData'
  );

  console.log('Decoding data...');
  const firestoreReceived = DocumentEventData.decode(cloudEvent.data);

  const resource = firestoreReceived.value.name;
  const affectedDoc = firestore.doc(resource.split('/documents/')[1]);

  const curValue = firestoreReceived.value.fields.original.stringValue;
  const newValue = curValue.toUpperCase();

  if (curValue === newValue) {
    // Value is already upper-case
    // Don't perform a(nother) write to avoid infinite loops
    console.log('Value is already upper-case.');
    return;
  }

  console.log(`Replacing value: ${curValue} --> ${newValue}`);
  affectedDoc.set({
    original: newValue,
  });
});

Python

from cloudevents.http import CloudEvent
import functions_framework
from google.cloud import firestore
from google.events.cloud import firestore as firestoredata

client = firestore.Client()

# Converts strings added to /messages/{pushId}/original to uppercase
@functions_framework.cloud_event
def make_upper_case(cloud_event: CloudEvent) -> None:
    firestore_payload = firestoredata.DocumentEventData()
    firestore_payload._pb.ParseFromString(cloud_event.data)

    path_parts = firestore_payload.value.name.split("/")
    separator_idx = path_parts.index("documents")
    collection_path = path_parts[separator_idx + 1]
    document_path = "/".join(path_parts[(separator_idx + 2) :])

    print(f"Collection path: {collection_path}")
    print(f"Document path: {document_path}")

    affected_doc = client.collection(collection_path).document(document_path)

    cur_value = firestore_payload.value.fields["original"].string_value
    new_value = cur_value.upper()

    if cur_value != new_value:
        print(f"Replacing value: {cur_value} --> {new_value}")
        affected_doc.set({"original": new_value})
    else:
        # Value is already upper-case
        # Don't perform a second write (which can trigger an infinite loop)
        print("Value is already upper-case.")

Go


// Package upper contains a Firestore Cloud Function.
package upper

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"strings"

	"cloud.google.com/go/firestore"
	firebase "firebase.google.com/go/v4"
	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
	"github.com/googleapis/google-cloudevents-go/cloud/firestoredata"
	"google.golang.org/protobuf/proto"
)

// set the GOOGLE_CLOUD_PROJECT environment variable when deploying.
var projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")

// client is a Firestore client, reused between function invocations.
var client *firestore.Client

func init() {
	// Use the application default credentials.
	conf := &firebase.Config{ProjectID: projectID}

	// Use context.Background() because the app/client should persist across
	// invocations.
	ctx := context.Background()

	app, err := firebase.NewApp(ctx, conf)
	if err != nil {
		log.Fatalf("firebase.NewApp: %v", err)
	}

	client, err = app.Firestore(ctx)
	if err != nil {
		log.Fatalf("app.Firestore: %v", err)
	}

	// Register cloud event function
	functions.CloudEvent("MakeUpperCase", MakeUpperCase)
}

// MakeUpperCase is triggered by a change to a Firestore document. It updates
// the `original` value of the document to upper case.
func MakeUpperCase(ctx context.Context, e event.Event) error {
	var data firestoredata.DocumentEventData
	if err := proto.Unmarshal(e.Data(), &data); err != nil {
		return fmt.Errorf("proto.Unmarshal: %w", err)
	}

	if data.GetValue() == nil {
		return errors.New("Invalid message: 'Value' not present")
	}

	fullPath := strings.Split(data.GetValue().GetName(), "/documents/")[1]
	pathParts := strings.Split(fullPath, "/")
	collection := pathParts[0]
	doc := strings.Join(pathParts[1:], "/")

	var originalStringValue string
	if v, ok := data.GetValue().GetFields()["original"]; ok {
		originalStringValue = v.GetStringValue()
	} else {
		return errors.New("Document did not contain field \"original\"")
	}

	newValue := strings.ToUpper(originalStringValue)
	if originalStringValue == newValue {
		log.Printf("%q is already upper case: skipping", originalStringValue)
		return nil
	}
	log.Printf("Replacing value: %q -> %q", originalStringValue, newValue)

	newDocumentEntry := map[string]string{"original": newValue}
	_, err := client.Collection(collection).Doc(doc).Set(ctx, newDocumentEntry)
	if err != nil {
		return fmt.Errorf("Set: %w", err)
	}
	return nil
}

Java

import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
import com.google.cloud.firestore.SetOptions;
import com.google.cloud.functions.CloudEventsFunction;
import com.google.events.cloud.firestore.v1.DocumentEventData;
import com.google.events.cloud.firestore.v1.Value;
import com.google.protobuf.InvalidProtocolBufferException;
import io.cloudevents.CloudEvent;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;

public class FirebaseFirestoreReactive implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(FirebaseFirestoreReactive.class.getName());
  private final Firestore firestore;

  private static final String FIELD_KEY = "original";
  private static final String APPLICATION_PROTOBUF = "application/protobuf";

  public FirebaseFirestoreReactive() {
    this(FirestoreOptions.getDefaultInstance().getService());
  }

  public FirebaseFirestoreReactive(Firestore firestore) {
    this.firestore = firestore;
  }

  @Override
  public void accept(CloudEvent event)
      throws InvalidProtocolBufferException, InterruptedException, ExecutionException {
    if (event.getData() == null) {
      logger.warning("No data found in event!");
      return;
    }

    if (!event.getDataContentType().equals(APPLICATION_PROTOBUF)) {
      logger.warning(String.format("Found unexpected content type %s, expected %s",
          event.getDataContentType(),
          APPLICATION_PROTOBUF));
      return;
    }

    DocumentEventData firestoreEventData = DocumentEventData
        .parseFrom(event.getData().toBytes());

    // Get the fields from the post-operation document snapshot
    // https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents#Document
    Map<String, Value> fields = firestoreEventData.getValue().getFieldsMap();
    if (!fields.containsKey(FIELD_KEY)) {
      logger.warning("Document does not contain original field");
      return;
    }
    String currValue = fields.get(FIELD_KEY).getStringValue();
    String newValue = currValue.toUpperCase();

    if (currValue.equals(newValue)) {
      logger.info("Value is already upper-case");
      return;
    }

    // Retrieve the document name from the resource path:
    // projects/{project_id}/databases/{database_id}/documents/{document_path}
    String affectedDoc = firestoreEventData.getValue()
        .getName()
        .split("/documents/")[1]
        .replace("\"", "");

    logger.info(String.format("Replacing values: %s --> %s", currValue, newValue));

    // Wait for the async call to complete
    this.firestore
        .document(affectedDoc)
        .set(Map.of(FIELD_KEY, newValue), SetOptions.merge())
        .get();
  }
}

C#

using CloudNative.CloudEvents;
using Google.Cloud.Firestore;
using Google.Cloud.Functions.Framework;
using Google.Cloud.Functions.Hosting;
using Google.Events.Protobuf.Cloud.Firestore.V1;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace FirestoreReactive;

public class Startup : FunctionsStartup
{
    public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services) =>
        services.AddSingleton(FirestoreDb.Create());
}

// Register the startup class to provide the Firestore dependency.
[FunctionsStartup(typeof(Startup))]
public class Function : ICloudEventFunction<DocumentEventData>
{
    private readonly ILogger _logger;
    private readonly FirestoreDb _firestoreDb;

    public Function(ILogger<Function> logger, FirestoreDb firestoreDb) =>
        (_logger, _firestoreDb) = (logger, firestoreDb);

    public async Task HandleAsync(CloudEvent cloudEvent, DocumentEventData data, CancellationToken cancellationToken)
    {
        // Get the recently-written value. This expression will result in a null value
        // if any of the following is true:
        // - The event doesn't contain a "new" document
        // - The value doesn't contain a field called "original"
        // - The "original" field isn't a string
        string currentValue = data.Value?.ConvertFields().GetValueOrDefault("original") as string;
        if (currentValue is null)
        {
            _logger.LogWarning($"Event did not contain a suitable document");
            return;
        }

        string newValue = currentValue.ToUpperInvariant();
        if (newValue == currentValue)
        {
            _logger.LogInformation("Value is already upper-cased; no replacement necessary");
            return;
        }

        // The CloudEvent subject is "documents/x/y/...".
        // The Firestore SDK FirestoreDb.Document method expects a reference relative to
        // "documents" (so just the "x/y/..." part). This may be simplified over time.
        if (cloudEvent.Subject is null || !cloudEvent.Subject.StartsWith("documents/"))
        {
            _logger.LogWarning("CloudEvent subject is not a document reference.");
            return;
        }
        string documentPath = cloudEvent.Subject.Substring("documents/".Length);

        _logger.LogInformation("Replacing '{current}' with '{new}' in '{path}'", currentValue, newValue, documentPath);
        await _firestoreDb.Document(documentPath).UpdateAsync("original", newValue);
    }
}

대문자로 변환 함수 배포

  1. 아직 설정하지 않았다면 Firestore 데이터베이스를 설정합니다.

  2. 다음 명령어를 사용하여 companies/{CompanyId} 문서에 대한 쓰기 이벤트로 트리거되는 함수를 배포합니다.

    gcloud functions deploy FUNCTION_NAME \
    --gen2 \
    --runtime=RUNTIME \
    --trigger-location=TRIGGER REGION \
    --region=REGION \
    --source=. \
    --entry-point=ENTRY_POINT \
    --trigger-event-filters=type=google.cloud.firestore.document.v1.written \
    --trigger-event-filters=database='(default)' \
    --trigger-event-filters-path-pattern=document='messages/{pushId}'
    

    다음을 바꿉니다.

    • FUNCTION_NAME: 배포된 함수의 이름입니다.
    • RUNTIME: 함수에서 사용하는 언어 런타임입니다.
    • REGION: 함수를 배포할 리전입니다.
    • TRIGGER_REGION: 트리거의 위치이며 Firestore 데이터베이스 리전과 동일해야 합니다.
    • ENTRY_POINT: 소스 코드에 있는 함수의 진입점입니다. 이는 함수가 실행될 때 실행되는 코드입니다.

    다른 필드는 다음과 같이 그대로 사용합니다.

    • --trigger-event-filters=type=google.cloud.firestore.document.v1.writtengoogle.cloud.firestore.document.v1.written 이벤트 유형에 따라 문서가 생성, 업데이트 또는 삭제될 때 함수가 트리거되도록 지정합니다.
    • --trigger-event-filters=database='(default)'는 Firestore 데이터베이스를 지정합니다. 기본 데이터베이스 이름으로는 (default)를 사용합니다.
    • --trigger-event-filters-path-pattern=document='messages/{pushId}'은 관련 변경사항을 모니터링해야 하는 문서의 경로 패턴을 제공합니다. 이 경로 패턴은 messages 컬렉션의 모든 문서를 모니터링해야 함을 나타냅니다. 자세한 내용은 경로 패턴 이해를 참조하세요.

대문자로 변환 함수 테스트

방금 배포한 대문자로 변환 함수를 테스트하려면 Firestore 데이터베이스에서 messages 컬렉션을 설정합니다.

  1. Firestore 데이터 페이지로 이동합니다.

  2. 컬렉션 시작을 클릭합니다.

  3. 컬렉션 ID로 messages를 지정합니다.

  4. 컬렉션의 첫 번째 문서 추가를 시작하려면 첫 번째 문서 추가에서 자동 생성된 문서 ID를 수락합니다.

  5. 배포된 함수를 트리거하려면 필드 이름이 'original'이고 필드 값이 소문자인 문서를 추가합니다. 예를 들면 다음과 같습니다.

    Firestore 컬렉션 만들기를 보여주는 스크린샷

  6. 문서를 저장하면 값 필드의 소문자가 대문자로 변환됩니다.

    나중에 필드 값을 수정하여 소문자를 포함하면 함수를 다시 트리거하여 모든 소문자를 대문자로 변환합니다.

제한사항

Cloud Functions용 Firestore 트리거의 다음 제한사항에 유의하세요.

  • 순서는 보장되지 않습니다. 급격하게 변경하면 예기치 않은 순서로 함수 호출이 트리거될 수 있습니다.
  • 이벤트는 최소 1회 전송되지만 하나의 이벤트에 함수가 여러 번 호출될 수 있습니다. 정확히 한 번에 처리하는 메커니즘에 의존하지 말고 멱등 함수를 작성하세요.
  • Datastore 모드의 Cloud Firestore에는 Cloud Functions(2세대)가 필요합니다. Cloud Functions(1세대)는 Datastore 모드를 지원하지 않습니다.
  • Cloud Functions(1세대)는 '(기본값)' 데이터베이스에서만 작동하며 이름이 지정된 Firestore 데이터베이스를 지원하지 않습니다. Cloud Functions(2세대)를 사용하여 이름이 지정된 데이터베이스의 이벤트를 구성하세요.
  • 트리거는 단일 데이터베이스와 연결됩니다. 여러 데이터베이스와 일치하는 트리거를 만들 수 없습니다.
  • 데이터베이스를 삭제해도 해당 데이터베이스의 트리거가 자동으로 삭제되지 않습니다. 트리거가 이벤트 제공을 중지하지만 트리거를 삭제하기 전까지 계속 존재합니다.
  • 일치하는 이벤트가 최대 요청 크기를 초과하면 이벤트가 Cloud Functions(1세대)로 전달되지 않을 수 있습니다.
    • 요청 크기로 인해 전달되지 않은 이벤트는 플랫폼 로그에 로깅되고 프로젝트의 로그 사용량에 포함됩니다.
    • 이러한 로그는 로그 탐색기에서 '크기가 1세대... 한도를 초과하여 Cloud 함수에 이벤트를 전송할 수 없음'이라는 error 심각도의 메시지와 함께 확인할 수 있습니다. functionName 필드에서 함수 이름을 확인할 수 있습니다. receiveTimestamp 필드가 지금부터 1시간 이내인 경우 타임스탬프 전후의 스냅샷과 함께 해당 문서를 읽어 실제 이벤트 콘텐츠를 추론할 수 있습니다.
    • 이러한 주기를 피하려면 다음을 수행하면 됩니다.
      • Cloud Functions(2세대)로 마이그레이션 및 업그레이드
      • 문서 크기 축소
      • 해당 Cloud Functions 삭제
    • 제외를 사용하여 로깅 자체를 사용 중지할 수 있지만 그래도 문제가 되는 이벤트가 전송되지 않습니다.