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
[null,null,["最后更新时间 (UTC):2025-08-17。"],[],[],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"]]