Cloud Functions(2세대)를 사용하면 커스텀 이벤트에 대한 응답으로 함수를 트리거할 수 있습니다. Cloud Functions용 Firebase SDK에서 기본적으로 지원하는 Firebase 이벤트와는 달리, 특별 이벤트 또는 추가 이벤트 제공업체에서 제공하는 이벤트입니다.
앱은 커스텀 이벤트 트리거를 통해 Firebase Extensions에서 제공하는 이벤트에 응답하거나 자체 커스텀 이벤트를 게시하고 이에 대한 응답으로 함수를 트리거할 수 있습니다.
예를 들어 게임 앱에서는 상위 10개의 경쟁사 리더보드에 참여하거나 리더보드에서 나갈 때 사용자에게 알림을 전송하려고 할 수 있습니다. 이 앱은 기본 채널에 리더보드 이벤트를 게시한 후 타겟팅된 푸시 알림을 사용자에게 전송하는 함수에서 이벤트를 처리할 수 있습니다.
또 다른 예로 앱에서 큰 이미지를 처리하도록 설계된 확장 프로그램은 이미지 크기 조절 완료 시 이벤트를 내보낼 수 있습니다. 이 확장 프로그램이 설치된 앱은 크기가 조절된 버전의 이미지를 가리키도록 앱의 링크를 업데이트하여 완료 이벤트를 처리할 수 있습니다.
채널에 이벤트 게시
Eventarc 이벤트는 채널에 게시됩니다.
채널은 관련 이벤트를 그룹화하고 액세스 권한을 관리하는 방법입니다. 확장 프로그램을 설치하거나 커스텀 이벤트를 사용하는 함수를 배포하면 Firebase에서 us-central1 리전에 firebase라는 기본 채널을 자동으로 만듭니다. Firebase Admin SDK는 채널에 게시하기 위한 eventarc 하위 패키지를 제공합니다.
기본 채널을 사용하여 신뢰할 수 있는 서버(또는 다른 함수)에서 이벤트를 게시하려면 다음 안내를 따르세요.
import{getEventarc}from'firebase-admin/eventarc';getEventarc().channel().publish({type:'achieved-leaderboard',subject:'Welcome to the top 10',data:{message:'You have achieved the nth position in our leaderboard! To see . . .'}});
Firebase는 기본 채널을 자동으로 만드는 것 외에도 이벤트 소스를 지정하는 EVENTARC_CLOUD_EVENT_SOURCE 환경 변수를 설정합니다. Cloud Functions for Firebase 외부에 이벤트를 게시하는 경우 source 필드를 이벤트 페이로드에 명시적으로 추가해야 합니다.
exports.onimageresized=onCustomEventPublished("firebase.extensions.storage-resize-images.v1.complete",(event)=>{logger.info("Received image resize completed event",event);// For example, write resized image details into Firestore.returngetFirestore().collection("images").doc(event.subject.replace("/","_"))// original file path.set(event.data);// resized images paths and sizes});
@eventarc_fn.on_custom_event_published(event_type="firebase.extensions.storage-resize-images.v1.complete")defonimageresized(event:eventarc_fn.CloudEvent)-> None:print("Received image resize completed event: ",event.type)ifnotisinstance(event.subject,str):print("No 'subject' data.")return# For example, write resized image details into Firestore.firestore_client:google.cloud.firestore.Client=firestore.client()collection=firestore_client.collection("images")doc=collection.document(event.subject.replace("/","_"))# original file pathdoc.set(event.data)# resized images paths and sizes
특정 확장 프로그램마다 이벤트 객체에서 반환되는 페이로드는 애플리케이션 흐름에서 커스텀 로직을 수행하는 데 사용할 수 있는 데이터를 제공합니다. 이 경우 함수는 Admin SDK를 사용하여 크기가 조절된 이미지에 대한 메타데이터를 Cloud Firestore의 컬렉션에 복사하고 이벤트에서 제공하는 subject에서 파일 이름을 가져오며 이벤트에서 제공하는 data에서 메타데이터를 저장합니다.
기본 채널 이외의 채널에서 이벤트 게시 및 처리
맞춤 채널은 특별한 권한이 필요하거나 기타 요구사항을 충족하고 모든 이벤트에 동일한 수준의 가시성과 액세스를 원하지 않는 경우에 유용할 수 있습니다. Google Cloud 콘솔을 사용하여 자체 채널을 만들 수 있습니다. 이벤트 게시 및 구독은 동일한 채널에서 수행해야 합니다.
기본 채널 이외의 채널에 커스텀 이벤트가 게시되는 경우 함수 코드에서 채널을 지정해야 합니다. 예를 들어 us-west1 위치의 기본 채널 이외의 채널에 게시된 이벤트를 처리하려면 다음과 같이 채널을 지정해야 합니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-05(UTC)"],[],[],null,["\u003cbr /\u003e\n\nWith Cloud Functions (2nd gen), you can trigger functions in response to *custom\nevents* . These are events provided by special or additional event providers, as\nopposed to the Firebase events natively supported by the Firebase SDK for Cloud Functions.\nVia custom event triggers, your app can respond to events provided by\nFirebase Extensions, or you can publish your own custom\nevents and trigger functions in response to them.\n| **Note:** This feature is a public preview. This means that the functionality might change in backward-incompatible ways. A preview release is not subject to any SLA or deprecation policy and may receive limited or no support.\n\nAll custom events conform to the\n[CloudEvents JSON event format](https://cloud.google.com/eventarc/docs/workflows/cloudevents)\nand are published to [Eventarc](https://cloud.google.com/eventarc/docs/overview).\nEventarc\n[usage fees](https://cloud.google.com/eventarc/pricing) apply.\n\nTrigger functions with custom events\n\nYou can publish custom events (or obtain events from Firebase extensions) and\ntrigger functions in response to those events by implementing this basic flow:\n\n1. Publish the desired events to an Eventarc channel, or identify available events provided by an extension that you have installed.\n2. In your function code, subscribe to events on the Eventarc channel with an event handler.\n3. In the function, parse the payload returned in the CloudEvent object and perform whatever custom logic your app requires.\n\nFor example, a game app might want to send notifications to users as they enter\nor leave the leaderboard of top ten competitors. This app could publish\nleaderboard events to the default channel, and then handle the event in a\nfunction that sends targeted push notifications to users.\n\nIn another\nexample, an extension designed to help apps process large images might emit an\nevent on the completion of image resizing. Apps with this extension installed\ncould handle the completion event by updating links in the app to point to\nresized versions of the image.\n\nPublish an event to a channel\n\nEventarc events are published into\n[channels](https://cloud.google.com/eventarc/docs/third-parties/create-channels).\nChannels are a way to group related events and manage access\npermissions. When you install an extension or deploy a function that consumes\ncustom events, Firebase automatically creates a default channel named\n`firebase` in the `us-central1` region. The Firebase Admin SDK provides\nan `eventarc` subpackage for publishing to channels.\n\nTo publish an event from a trusted server (or another function) using the\ndefault channel: \n\n import {getEventarc} from 'firebase-admin/eventarc';\n\n getEventarc().channel().publish({\n type: 'achieved-leaderboard',\n subject: 'Welcome to the top 10',\n data: {\n message: 'You have achieved the nth position in our leaderboard! To see . . .'\n }\n });\n\nIn addition to automatically creating the default channel, Firebase sets the\nenvironment variable `EVENTARC_CLOUD_EVENT_SOURCE`, which specifies the source\nof the event. If you are publishing events outside of Cloud Functions for Firebase,\nyou'll need to explicitly add the `source` field in your event payload.\n\nHandle custom events\n\nYou can handle all custom events, including extensions events, with the\n[`onCustomEventPublished`](/docs/reference/functions/2nd-gen/node/firebase-functions.eventarc#eventarconcustomeventpublished) or\n[`on_custom_event_published`](/docs/reference/functions/2nd-gen/python/firebase_functions.eventarc_fn#on_custom_event_published)\nhandlers. First, import this handler from the Eventarc SDK along with the\nFirebase Admin SDK: \n\nNode.js \n\n const {onCustomEventPublished} = require(\"firebase-functions/v2/eventarc\");\n const logger = require(\"firebase-functions/logger\");\n const {initializeApp} = require(\"firebase-admin/app\");\n const {getFirestore} = require(\"firebase-admin/firestore\"); \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/custom-events/functions/index.js#L18-L22\n\nPython \n\n from firebase_admin import firestore, initialize_app\n from firebase_functions import eventarc_fn \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/custom-events/functions/main.py#L16-L17\n\nIn your function code, pass in the event name as shown for the example function: \n\nNode.js \n\n exports.onimageresized = onCustomEventPublished(\n \"firebase.extensions.storage-resize-images.v1.complete\",\n (event) =\u003e {\n logger.info(\"Received image resize completed event\", event);\n // For example, write resized image details into Firestore.\n return getFirestore()\n .collection(\"images\")\n .doc(event.subject.replace(\"/\", \"_\")) // original file path\n .set(event.data); // resized images paths and sizes\n }); \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/custom-events/functions/index.js#L28-L37\n\nPython \n\n @eventarc_fn.on_custom_event_published(\n event_type=\"firebase.extensions.storage-resize-images.v1.complete\")\n def onimageresized(event: eventarc_fn.CloudEvent) -\u003e None:\n print(\"Received image resize completed event: \", event.type)\n\n if not isinstance(event.subject, str):\n print(\"No 'subject' data.\")\n return\n\n # For example, write resized image details into Firestore.\n firestore_client: google.cloud.firestore.Client = firestore.client()\n collection = firestore_client.collection(\"images\")\n doc = collection.document(event.subject.replace(\"/\", \"_\")) # original file path\n doc.set(event.data) # resized images paths and sizes \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/custom-events/functions/main.py#L25-L38\n\nFor each particular extension, the payload returned in the event object provides\ndata you can use to perform custom logic for your application flow. In this\ncase, the function uses the Admin SDK to copy metadata about the resized\nimage to a collection in Cloud Firestore, obtaining the filename from the\n`subject` provided by the event, and saving metadata from the `data` provided\nby the event.\n\nPublish and handle events on non-default channels\n\nCustom channels can be useful for cases where you have special permission needs\nor other requirements, and don't want the same level of visibility and access\nfor all events. You can create your own channels using the\n[Google Cloud console](https://console.cloud.google.com/eventarc/channels). Publishing and subscribing for events must be done on the same channel.\n\nIn cases where a custom event is published on a non-default channel,\nyou'll need to specify the channel in your function code. For example, if you\nwant to handle events that are published in a non-default channel for the\n`us-west1` location, you need to specify the channel as shown: \n\nNode.js \n\n import { onCustomEventPublished } from \"firebase-functions/v2/eventarc\";\n\n export const func = onCustomEventPublished(\n {\n eventType: \"firebase.extensions.storage-resize-images.v1.complete\",\n channel: \"locations/us-west1/channels/firebase\",\n region: \"us-west1\",\n },\n (event) =\u003e { ... });\n\nPython \n\n @eventarc_fn.on_custom_event_published(\n event_type=\"firebase.extensions.storage-resize-images.v1.complete\",\n channel=\"locations/us-west1/channels/firebase\",\n region=\"us-west1\")\n def onimageresizedwest(event: eventarc_fn.CloudEvent) -\u003e None:\n print(\"Received image resize completed event: \", event.type)\n # ... \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/custom-events/functions/main.py#L43-L59"]]