새 함수를 만드는 경우 Cloud Run의
콘솔 빠른 시작을 참고하세요.
Firebase 실시간 데이터베이스 변경사항 수신 대기
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
이 함수는 Firebase 실시간 데이터베이스 참조 변경으로 트리거됩니다. 변경 소스, 데이터, 델타가 출력됩니다.
코드 샘플
Go
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Java
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Node.js
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Python
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis function is activated when a change occurs in a Firebase Realtime Database reference.\u003c/p\u003e\n"],["\u003cp\u003eThe function's primary actions include logging the source of the database change, the data affected by the change, and the specific delta (the difference before and after the change).\u003c/p\u003e\n"],["\u003cp\u003eAuthentication for Cloud Run functions is achieved by setting up Application Default Credentials, which is detailed in a linked documentation.\u003c/p\u003e\n"],["\u003cp\u003eThe examples show how to implement this function using four different languages: Go, Java, Node.js, and Python.\u003c/p\u003e\n"]]],[],null,["# Listen to Firebase Realtime Database changes\n\nThis function is triggered by a change to a Firebase Realtime Database reference. It prints the source of the change, the data, and the delta.\n\nCode sample\n-----------\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package rtdb contains a Cloud Function triggered by a Firebase Realtime Database\n // event.\n package rtdb\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"log\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n \t\"github.com/cloudevents/sdk-go/v2/event\"\n \t\"github.com/googleapis/google-cloudevents-go/firebase/databasedata\"\n \t\"google.golang.org/protobuf/encoding/protojson\"\n )\n\n func init() {\n \tfunctions.CloudEvent(\"HelloRTDB\", HelloRTDB)\n }\n\n // HelloRTDB handles changes to a Firebase RTDB.\n func HelloRTDB(ctx context.Context, e event.Event) error {\n \tunmarshalOptions := protojson.UnmarshalOptions{DiscardUnknown: true}\n\n \tvar data databasedata.ReferenceEventData\n \tif err := unmarshalOptions.Unmarshal(e.Data(), &data); err != nil {\n \t\treturn fmt.Errorf(\"Unmarshal: %w\", err)\n \t}\n \tlog.Printf(\"Function triggered by change to: %v\", e.Source())\n \tlog.Printf(\"Data: %+v\", data.GetData())\n \tlog.Printf(\"Delta: %+v\", data.GetDelta())\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.google.cloud.functions.CloudEventsFunction;\n import com.google.events.firebase.database.v1.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html;\n import com.google.protobuf.util.https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.html;\n import io.cloudevents.CloudEvent;\n import java.nio.charset.StandardCharsets;\n import java.util.logging.Logger;\n\n public class FirebaseRtdb implements CloudEventsFunction {\n private static final Logger logger = Logger.getLogger(FirebaseRtdb.class.getName());\n\n @Override\n public void accept(CloudEvent event) throws Exception {\n if (event.getData() == null) {\n logger.info(\"No data found in event\");\n return;\n }\n\n https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html.Builder builder = https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html.newBuilder();\n https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.html.https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.Parser.html jsonParser = https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.html.parser().https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.Parser.html#com_google_protobuf_util_JsonFormat_Parser_ignoringUnknownFields__();\n jsonParser.merge(new String(event.getData().toBytes(), StandardCharsets.UTF_8), builder);\n https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html data = builder.build();\n\n logger.info(\"Function triggered by change to: \" + event.getSource().toString());\n\n if (data.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html#com_google_events_firebase_database_v1_ReferenceEventData_hasDelta__()) {\n logger.info(\"Delta: \" + data.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html#com_google_events_firebase_database_v1_ReferenceEventData_getDelta__().toString());\n }\n\n if (data.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html#com_google_events_firebase_database_v1_ReferenceEventData_hasData__()) {\n logger.info(\"Data: \" + data.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html#com_google_events_firebase_database_v1_ReferenceEventData_getData__().toString());\n }\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n /**\n * Cloud Event Function triggered by a change to a Firebase RTDB reference.\n *\n * @param {!Object} event The Cloud Functions event.\n */\n const functions = require('@google-cloud/functions-framework');\n\n functions.cloudEvent('helloRTDB', event =\u003e {\n console.log(`Function triggered by change to: ${event.source}`);\n console.log('Data:');\n console.log(JSON.stringify(event.data.data, null, 2));\n console.log('Delta:');\n console.log(JSON.stringify(event.data.delta, null, 2));\n });\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import json\n\n from cloudevents.http import CloudEvent\n import functions_framework\n\n\n @functions_framework.cloud_event\n def hello_rtdb(event: CloudEvent) -\u003e None:\n \"\"\"Triggered by a change to a Firebase RTDB reference.\n Args:\n event: Cloud Event triggered by change to Firebase Real Time Database.\n \"\"\"\n print(f\"Function triggered by change to: {event['source']}\")\n print(\"Data:\")\n print(json.dumps(event.data[\"data\"]))\n print(\"Delta:\")\n print(json.dumps(event.data[\"delta\"]))\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]