확장 프로그램에 대한 Cloud Functions 작성

확장 프로그램을 만들 때는 자체 프로젝트에서만 사용되는 함수를 작성하는 것과 동일한 방식으로 Cloud Functions를 사용하여 로직을 작성합니다. extension.yaml 파일에서 함수를 선언하고 사용자가 확장 프로그램을 설치하면 이 함수가 프로젝트에 배포됩니다.

Cloud Functions 사용에 대한 일반적인 정보는 Cloud Functions 문서를 참조하세요.

1세대 및 2세대 Cloud Functions

Firebase는 1세대 및 2세대 Cloud Functions를 모두 지원합니다. 하지만 Firebase Extensions는 현재 특정 트리거 유형에 사용할 수 있는 Cloud 함수의 세대에 몇 가지 제한사항이 있습니다. 이러한 이유로 많은 확장 프로그램에는 1세대 및 2세대 함수가 혼합되어 있습니다.

각 트리거 유형별 함수 생성 지원에 관한 설명은 아래에 나와 있습니다.

특별 고려사항

  • 일부 함수 정의에서는 extension.yaml 파일에도 지정된 정보를 지정해야 합니다. 예를 들어 Cloud Firestore에는 확인할 문서 패턴을 지정하는 document() 메서드가 있고 이에 상응하는 extension.yaml의 선언에는 동일한 것을 지정하는 resource 필드가 있습니다.

    이러한 상황에서는 extension.yaml 파일에 지정된 구성이 사용되며 함수 정의에 지정된 구성은 무시됩니다.

    문서화를 위해 함수 정의에 구성된 값을 지정하는 것이 일반적입니다. 이 페이지의 예시는 이 패턴을 따릅니다.

  • Cloud Functions 1세대 SDK에는 1세대 함수에서 매개변수화된 값을 이용하여 작업하는 데 사용할 수 있는 functions.config() 메서드와 functions:config:set CLI 명령어가 있습니다. 이 기법은 Cloud Functions에서 지원 중단되었으며 확장 프로그램에서 전혀 작동하지 않습니다. 대신 functions.params 모듈(권장) 또는 process.env를 사용하세요.

TypeScript 사용

자체 확장 프로그램 개발에 대한 문서에서는 대부분 JavaScript를 사용하는 Firebase용 Cloud Functions 워크플로를 설명합니다. 하지만 TypeScript를 사용하여 함수를 작성할 수도 있습니다.

실제로 모든 공식 Firebase 확장 프로그램이 TypeScript로 작성되었습니다. 이러한 확장 프로그램을 검토하여 확장 프로그램에 TypeScript 사용 시 권장사항을 확인할 수 있습니다.

TypeScript에서 확장 프로그램의 함수를 작성하는 경우 확장 프로그램을 설치하기 전에 다음을 수행해야 합니다.

  1. 확장 프로그램의 함수 소스 코드를 JavaScript로 컴파일합니다.

    firebase ext:dev:init 명령어를 사용하면 함수 작성에 TypeScript를 사용하도록 선택할 수 있습니다. 이 명령어는 완전하고 설치 가능한 확장 프로그램은 물론 npm run build로 실행할 수 있는 빌드 스크립트도 제공합니다.

  2. package.json 파일에서 main 필드가 생성된 JavaScript를 가리키도록 합니다.

  3. 로컬 소스에서 확장 프로그램을 설치하거나 업로드하는 경우 먼저 TypeScript 파일을 컴파일합니다.

지원되는 함수 트리거

HTTP 트리거

HTTP 트리거 함수는 공개 https 엔드포인트에 배포되며 엔드포인트에 액세스할 때 실행됩니다.

HTTP 트리거 함수를 작성하는 방법에 대한 자세한 내용은 Cloud Functions 문서의 HTTP 요청을 통한 함수 호출을 참조하세요.

함수 정의(1세대만)

import { https } from "firebase-functions/v1";

export const yourFunctionName = https.onRequest(async (req, resp) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      runtime: nodejs16
      httpsTrigger: {}
  - name: anotherFunction
    type: ...

호출 가능 함수

호출 가능 함수는 HTTP 트리거 함수와 유사하지만 클라이언트 측 코드에서 편리하게 호출할 수 있게 해주는 프로토콜을 구현합니다.

호출 가능 함수 사용에 대한 자세한 내용은 Cloud Functions 문서의 앱에서 함수 호출을 참조하세요.

함수 정의(1세대만)

import { https } from "firebase-functions/v1";

export const yourFunctionName = https.onCall(async (data, context) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      runtime: nodejs16
      httpsTrigger: {}
  - name: anotherFunction
    type: ...

예약된 함수 트리거

예약된 함수는 맞춤설정 가능한 일정에 따라 반복적으로 실행됩니다.

예약된 함수 작성에 대한 자세한 내용은 Cloud Functions 문서의 함수 예약을 참조하세요.

함수 정의(1세대만)

import { pubsub } from "firebase-functions/v1";

export const yourFunctionName = pubsub.schedule("every 6 hours").onRun((context) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      scheduleTrigger:
        schedule: 'every 5 minutes'
  - name: anotherFunction
    type: ...

다음은 scheduleTrigger에 사용 가능한 하위 필드입니다.

필드 설명
schedule
(필수)

함수를 실행할 빈도입니다.

이 필드는 두 구문을 사용하는 문자열을 허용할 수 있습니다(작은따옴표로 래핑해야 함).

timeZone
(선택사항)

일정이 실행될 시간대입니다.

사용자가 확장 프로그램을 설치할 때 일정을 구성할 수 있도록 하려면 extension.yaml 파일에 새 매개변수를 추가하고 함수의 resource 선언에서 매개변수를 참조합니다.

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      scheduleTrigger:
        schedule: ${SCHEDULE_FREQUENCY}
  - name: anotherFunction
    type: ...

params:
  - param: SCHEDULE_FREQUENCY
    label: Schedule
    description: How often do you want to run yourFunctionName()?
    type: string
    default: 'every 5 minutes'  # Specifying a default is optional.
    required: true

태스크 큐 트리거

태스크 큐 함수는 확장 프로그램의 수명 주기 이벤트에서 또는 Admin SDK의 TaskQueue.enqueue() 메서드를 사용하여 확장 프로그램의 태스크 큐에 수동으로 추가될 때 트리거됩니다.

수명 주기 이벤트를 처리하는 함수를 작성하는 방법에 대한 자세한 내용은 확장 프로그램의 수명 주기 이벤트 처리를 참조하세요.

태스크 큐 함수 작성에 대한 자세한 내용은 Cloud Functions 문서의 Cloud Tasks로 큐에 함수 추가를 참조하세요.

함수 정의(1세대만)

import { tasks } from "firebase-functions/v1";

export const yourFunctionName = tasks.taskQueue().onDispatch(async (data, context) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: myTaskFunction
    type: firebaseextensions.v1beta.function
    description: >-
      Perform a task when triggered by a lifecycle event
    properties:
      taskQueueTrigger: {}

taskQueueTrigger 속성을 {} 또는 태스크 큐의 비율 제한과 재시도 동작을 미세 조정하는 옵션 맵으로 설정합니다(태스크 큐 미세 조정 참고).

확장 프로그램의 수명 주기 이벤트에서 함수를 트리거하려면 함수 이름과 선택적 처리 메시지가 있는 lifecycleEvents 레코드를 추가합니다. 이 메시지는 처리가 시작될 때 Firebase Console에 표시됩니다.

lifecycleEvents:
  onInstall:
    function: myTaskFunction
    processingMessage: Resizing your existing images
  onUpdate:
    function: myOtherTaskFunction
    processingMessage: Setting up your extension
  onConfigure:
    function: myOtherTaskFunction
    processingMessage: Setting up your extension

애널리틱스

애널리틱스 트리거 함수는 지정된 애널리틱스 이벤트가 로깅될 때 실행됩니다.

애널리틱스 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 Google 애널리틱스 트리거를 참조하세요.

함수 정의(1세대만)

import { analytics } from "firebase-functions/v1";

export const yourFunctionName = analytics.event("event_name").onLog((event, context) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: providers/google.firebase.analytics/eventTypes/event.log
        resource: projects/${PROJECT_ID}/events/ga_event
  - name: anotherFunction
    type: ...

사용자가 확장 프로그램을 설치할 때 리슨할 애널리틱스 이벤트를 구성할 수 있도록 하려면 extension.yaml 파일에 새 매개변수를 추가하고 함수의 resource 선언에서 매개변수를 참조합니다.

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: providers/google.firebase.analytics/eventTypes/event.log
        resource: projects/${PROJECT_ID}/events/${EVENT_NAME}
  - name: anotherFunction
    type: ...

params:
  - param: EVENT_NAME
    label: Analytics event
    description: What event do you want to respond to?
    type: string
    default: ga_event  # Specifying a default is optional.
    required: true

인증

인증 트리거 함수는 사용자가 생성되거나 삭제될 때 실행됩니다.

인증 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 Firebase 인증 트리거를 참조하세요.

함수 정의(1세대만)

import { auth } from "firebase-functions/v1";

export const yourFunctionName = auth.user().onCreate((user, context) => {
  // ...
});

export const yourFunctionName2 = auth.user().onDelete((user, context) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: providers/firebase.auth/eventTypes/user.create
        resource: projects/${PROJECT_ID}
  - name: anotherFunction
    type: ...

다음 표는 지원되는 각 인증 이벤트 유형을 지정하는 방법을 보여줍니다.

Cloud Functions 이벤트 트리거 eventType 설명
onCreate() providers/firebase.auth/eventTypes/user.create 새 사용자가 생성됨
onDelete() providers/firebase.auth/eventTypes/user.delete 사용자가 삭제됨

Cloud Firestore

Cloud Firestore 트리거 함수는 문서가 생성, 업데이트, 삭제될 때 실행됩니다.

Firestore 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 Cloud Firestore 트리거를 참조하세요.

함수 정의(1세대만)

import { firestore } from "firebase-functions/v1";

export const yourFunctionName = firestore.document("collection/{doc_id}")
  .onCreate((snapshot, context) => {
    // ...
  });

export const yourFunctionName2 = firestore.document("collection/{doc_id}")
  .onUpdate((change, context) => {
    // ...
  });

export const yourFunctionName3 = firestore.document("collection/{doc_id}")
  .onDelete((snapshot, context) => {
    // ...
  });

export const yourFunctionName4 = firestore.document("collection/{doc_id}")
  .onWrite((change, context) => {
    // onWrite triggers on creation, update, and deletion.
    // ...
  });

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: providers/cloud.firestore/eventTypes/document.write
        resource: projects/${PROJECT_ID}/databases/(default)/documents/collection/{documentID}
  - name: anotherFunction
    type: ...

다음 표는 지원되는 각 Cloud Firestore 이벤트 유형을 지정하는 방법을 보여줍니다.

Cloud Functions 이벤트 트리거 eventType 설명
onCreate() providers/cloud.firestore/eventTypes/document.create 새 문서가 생성됨
onDelete() providers/cloud.firestore/eventTypes/document.delete 문서가 삭제됨
onUpdate() providers/cloud.firestore/eventTypes/document.update 문서가 업데이트됨
onWrite() providers/cloud.firestore/eventTypes/document.write 문서가 생성, 삭제 또는 업데이트됨

사용자가 확장 프로그램을 설치할 때 문서 경로를 구성할 수 있도록 하려면 extension.yaml 파일에 새 매개변수를 추가하고 함수의 resource 선언에서 매개변수를 참조합니다.

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: providers/cloud.firestore/eventTypes/document.write
        resource: projects/${PROJECT_ID}/databases/(default)/documents/${YOUR_DOCUMENT_PATH}
  - name: anotherFunction
    type: ...

params:
  - param: YOUR_DOCUMENT_PATH
    label: Cloud Firestore path
    description: Where do you want to watch for changes?
    type: string
    default: path/to/{documentID}  # Specifying a default is optional.
    required: true

Pub/Sub

Pub/Sub 트리거 함수는 메시지가 특정 주제에 게시될 때 실행됩니다.

Pub/Sub 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 Pub/Sub 트리거를 참조하세요.

함수 정의(1세대만)

import { pubsub } from "firebase-functions/v1";

export const yourFunctionName = pubsub.topic("topic_name").onPublish((message, context) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: google.pubsub.topic.publish
        resource: projects/${PROJECT_ID}/topics/topic-name
  - name: anotherFunction
    type: ...

사용자가 확장 프로그램을 설치할 때 Pub/Sub 주제를 구성할 수 있도록 하려면 extension.yaml 파일에 새 매개변수를 추가하고 함수의 resource 선언에서 매개변수를 참조합니다.

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: google.pubsub.topic.publish
        resource: projects/${PROJECT_ID}/topics/${PUBSUB_TOPIC}
  - name: anotherFunction
    type: ...

params:
  - param: PUBSUB_TOPIC
    label: Pub/Sub topic
    description: Which Pub/Sub topic do you want to watch for messages?
    type: string
    default: topic-name  # Specifying a default is optional.
    required: true

실시간 데이터베이스

실시간 데이터베이스 트리거 함수는 지정된 패턴과 일치하는 경로가 생성, 업데이트 또는 삭제될 때 실행됩니다.

RTDB 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 실시간 데이터베이스 트리거를 참조하세요.

함수 정의(1세대만)

import { database } from "firebase-functions/v1";

export const yourFunctionName = database.ref("path/to/{item}")
  .onCreate((snapshot, context) => {
    // ...
  });

export const yourFunctionName2 = database.ref("path/to/{item}")
  .onUpdate((change, context) => {
    // ...
  });

export const yourFunctionName3 = database.ref("path/to/{item}")
  .onDelete((snapshot, context) => {
    // ...
  });

export const yourFunctionName4 = database.ref("path/to/{item}")
  .onWrite((change, context) => {
    // onWrite triggers on creation, update, and deletion.
    // ...
  });

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: providers/google.firebase.database/eventTypes/ref.create
        # DATABASE_INSTANCE (project's default instance) is an auto-populated
        # parameter value. You can also specify an instance.
        resource: projects/_/instances/${DATABASE_INSTANCE}/refs/path/to/{itemId}
  - name: anotherFunction
    type: ...

다음 표는 지원되는 각 Cloud Firestore 이벤트 유형을 지정하는 방법을 보여줍니다.

Cloud Functions 이벤트 트리거 eventType 설명
onCreate() providers/google.firebase.database/eventTypes/ref.create 데이터가 생성됨
onDelete() providers/google.firebase.database/eventTypes/ref.delete 데이터가 삭제됨
onUpdate() providers/google.firebase.database/eventTypes/ref.update 데이터가 업데이트됨
onWrite() providers/google.firebase.database/eventTypes/ref.write 데이터가 생성, 삭제 또는 업데이트됨

사용자가 확장 프로그램을 설치할 때 보려는 경로를 구성할 수 있도록 하려면 extension.yaml 파일에 새 매개변수를 추가하고 함수의 resource 선언에서 매개변수를 참조합니다.

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: providers/google.firebase.database/eventTypes/ref.create
        # DATABASE_INSTANCE (project's default instance) is an auto-populated
        # parameter value. You can also specify an instance.
        resource: projects/_/instances/${DATABASE_INSTANCE}/refs/${DB_PATH}
  - name: anotherFunction
    type: ...

params:
  - param: DB_PATH
    label: Realtime Database path
    description: Where do you want to watch for changes?
    type: string
    default: path/to/{itemId}  # Specifying a default is optional.
    required: true

원격 구성

원격 구성 트리거 함수는 프로젝트의 매개변수 템플릿이 업데이트될 때 실행됩니다.

원격 구성 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 원격 구성 트리거를 참조하세요.

함수 정의(1세대만)

import { remoteConfig } from "firebase-functions/v1";

export const yourFunctionName = remoteConfig.onUpdate((version, context) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: google.firebase.remoteconfig.update
        resource: projects/${PROJECT_ID}
  - name: anotherFunction
    type: ...

Cloud Storage

Cloud Storage 트리거 함수는 객체가 생성, 보관처리, 삭제될 때 또는 메타데이터가 변경될 때 실행됩니다.

Storage 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 Cloud Storage 트리거를 참조하세요.

함수 정의(1세대만)

import { storage } from "firebase-functions/v1";

export const yourFunctionName = storage.object().onFinalize((object, context) => {
  // ...
});

export const yourFunctionName2 = storage.object().onMetadataUpdate((object, context) => {
  // ...
});

export const yourFunctionName3 = storage.object().onArchive((object, context) => {
  // ...
});

export const yourFunctionName4 = storage.object().onDelete((object, context) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: google.storage.object.finalize
        # STORAGE_BUCKET (project's default bucket) is an auto-populated
        # parameter. You can also specify a bucket.
        resource: projects/_/buckets/${STORAGE_BUCKET}
  - name: anotherFunction
    type: ...

다음 표는 지원되는 각 Cloud Storage 이벤트 유형을 지정하는 방법을 보여줍니다.

Cloud Functions 이벤트 트리거 eventType 설명
onFinalize() google.storage.object.finalize 객체가 생성됨
onMetadataUpdate() google.storage.object.metadataUpdate 객체 메타데이터가 업데이트됨
onArchive() google.storage.object.archive 객체가 보관처리됨
onDelete() google.storage.object.delete 객체가 삭제됨

사용자가 확장 프로그램을 설치할 때 스토리지 버킷을 구성할 수 있도록 하려면 extension.yaml 파일에 새 매개변수를 추가하고 함수의 resource 선언에서 매개변수를 참조합니다.

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: google.storage.object.finalize
        resource: projects/_/buckets/${YOUR_BUCKET}
  - name: anotherFunction
    type: ...

params:
  - param: YOUR_BUCKET
    label: Cloud Storage bucket
    description: Which bucket do you want to watch for changes?
    type: selectResource
    resourceType: storage.googleapis.com/Bucket
    default: ${STORAGE_BUCKET}  # Specifying a default is optional.
    required: true

Test Lab

Test Lab 트리거 함수는 테스트 매트릭스가 테스트를 완료하면 실행됩니다.

Test Lab 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 Firebase Test Lab 트리거를 참조하세요.

함수 정의(1세대만)

import { testLab } from "firebase-functions/v1";

export const yourFunctionName = testLab.testMatrix().onComplete((matrix, context) => {
  // ...
});

리소스 선언(extension.yaml)

resources:
  - name: yourFunctionName
    type: firebaseextensions.v1beta.function
    properties:
      eventTrigger:
        eventType: google.testing.testMatrix.complete
        resource: projects/${PROJECT_ID}/testMatrices/{matrixId}
  - name: anotherFunction
    type: ...

Crashlytics 알림 트리거

Crashlytics 트리거 함수는 Crashlytics가 알림을 게시할 때 실행됩니다.

알림 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 Firebase 알림 트리거를 참조하세요.

함수 정의(2세대만)

import {
  onNewFatalIssuePublished,
  onNewNonfatalIssuePublished,
  onNewAnrIssuePublished,
  onRegressionAlertPublished,
  onVelocityAlertPublished,
  onStabilityDigestPublished,
} from "firebase-functions/v2/alerts/crashlytics";

export const yourFunctionName = onNewFatalIssuePublished((event) => {
  // ...
});

export const yourFunctionName2 = onNewNonfatalIssuePublished((event) => {
  // ...
});

export const yourFunctionName3 = onNewAnrIssuePublished((event) => {
  // ...
});

export const yourFunctionName4 = onRegressionAlertPublished((event) => {
  // ...
});

export const yourFunctionName5 = onVelocityAlertPublished((event) => {
  // ...
});

export const yourFunctionName6 = onStabilityDigestPublished((event) => {
  // ...
});

리소스 선언(extension.yaml)

apis:
  - apiName: eventarc.googleapis.com
    reason: Powers all events and triggers
  - apiName: run.googleapis.com
    reason: Powers 2nd-gen functions

resources:
  - name: yourfunctionname
    type: firebaseextensions.v1beta.v2function
    properties:
      buildConfig:
        runtime: nodejs16
      serviceConfig:
        availableMemory: 512M
      eventTrigger:
        eventType: google.firebase.firebasealerts.alerts.v1.published
        triggerRegion: global
        eventFilters:
          - attribute: alerttype
            value: crashlytics.newFatalIssue
  - name: anotherFunction
    type: ...

alerttype에 다음 값을 사용할 수 있습니다.

  • crashlytics.newFatalIssue
  • crashlytics.newNonfatalIssue
  • crashlytics.regression
  • crashlytics.stabilityDigest
  • crashlytics.velocity
  • crashlytics.newAnrIssue

Performance Monitoring 알림 트리거

Performance Monitoring에서 알림을 게시하면 Performance Monitoring 트리거 함수가 실행됩니다.

알림 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 Firebase 알림 트리거를 참조하세요.

함수 정의(2세대만)

import { onThresholdAlertPublished } from "firebase-functions/v2/alerts/performance";

export const yourFunctionName = onThresholdAlertPublished((event) => {
  // ...
});

리소스 선언(extension.yaml)

apis:
  - apiName: eventarc.googleapis.com
    reason: Powers all events and triggers
  - apiName: run.googleapis.com
    reason: Powers 2nd-gen functions

resources:
  - name: yourfunctionname
    type: firebaseextensions.v1beta.v2function
    properties:
      buildConfig:
        runtime: nodejs16
      serviceConfig:
        availableMemory: 512M
      eventTrigger:
        eventType: google.firebase.firebasealerts.alerts.v1.published
        triggerRegion: global
        eventFilters:
          - attribute: alerttype
            value: performance.threshold
  - name: anotherFunction
    type: ...

앱 배포 알림 트리거

앱 배포에서 알림을 게시하면 앱 배포 트리거 함수가 실행됩니다.

알림 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 Firebase 알림 트리거를 참조하세요.

함수 정의(2세대만)

import {
  onNewTesterIosDevicePublished,
  onInAppFeedbackPublished
} from "firebase-functions/v2/alerts/appDistribution";

export const yourFunctionName = onNewTesterIosDevicePublished((event) => {
  // ...
});

export const yourFunctionName2 = onInAppFeedbackPublished((event) => {
  // ...
});

리소스 선언(extension.yaml)

apis:
  - apiName: eventarc.googleapis.com
    reason: Powers all events and triggers
  - apiName: run.googleapis.com
    reason: Powers 2nd-gen functions

resources:
  - name: yourfunctionname
    type: firebaseextensions.v1beta.v2function
    properties:
      buildConfig:
        runtime: nodejs16
      serviceConfig:
        availableMemory: 512M
      eventTrigger:
        eventType: google.firebase.firebasealerts.alerts.v1.published
        triggerRegion: global
        eventFilters:
          - attribute: alerttype
            value: appDistribution.inAppFeedback
  - name: anotherFunction
    type: ...

alerttype에 다음 값을 사용할 수 있습니다.

  • appDistribution.newTesterIosDevice
  • appDistribution.inAppFeedback

커스텀 이벤트 트리거(Eventarc)

Eventarc 트리거 함수는 특정 이벤트 유형이 특정 채널에 게시될 때 실행됩니다.

Eventarc 트리거 함수를 작성하는 방법은 Cloud Functions 문서의 커스텀 이벤트 트리거 만들기 및 처리를 참조하세요.

확장 프로그램의 이벤트를 게시하여 사용자에게 확장 프로그램에 커스텀 로직을 삽입하는 방법을 제공할 수도 있습니다. 확장 프로그램에서 개발자가 제공한 커스텀 로직 사용을 참조하세요.

함수 정의(2세대만)

import { onCustomEventPublished } from "firebase-functions/v2/eventarc";

export const yourFunctionName = onCustomEventPublished((event) => {
  // ...
});

리소스 선언(extension.yaml)

apis:
  - apiName: eventarc.googleapis.com
    reason: Powers all events and triggers
  - apiName: run.googleapis.com
    reason: Powers 2nd-gen functions

resources:
  - name: yourfunctionname
    type: firebaseextensions.v1beta.v2function
    properties:
      # LOCATION is a user-configured parameter value specified by the user
      # during installation.
      location: ${param:LOCATION}
      buildConfig:
        runtime: nodejs16
      serviceConfig:
        availableMemory: 512M
        timeoutSeconds: 60
      eventTrigger:
        eventType: firebase.extensions.storage-resize-images.v1.complete
        channel: projects/${param:PROJECT_ID}/locations/us-central1/channels/firebase
  - name: anotherFunction
    type: ...

확장 프로그램이 설치될 때 채널이 이미 존재해야 합니다. 예를 들어 채널을 만드는 다른 확장 프로그램의 커스텀 이벤트를 사용하는 경우 사용자에게 먼저 해당 확장 프로그램을 설치하도록 안내합니다.

위의 예시에서는 us-central1 리전의 '기본' Firebase 채널에 대한 커스텀 이벤트 트리거를 만듭니다. 매개변수를 사용하여 채널 이름과 리전을 맞춤설정할 수 있습니다. 예를 들면 다음과 같습니다.


params:
  - param: EVENTARC_CHANNEL_NAME
    label: Eventarc channel name
    description: What is the name of the Eventarc channel.
    default: firebase
    type: string
    required: true

resources:
  - name: yourfunctionname
    type: firebaseextensions.v1beta.v2function
    properties:
      location: ${param:LOCATION}
      eventTrigger:
        eventType: firebase.extensions.storage-resize-images.v1.complete
        channel: projects/${param:PROJECT_ID}/locations/${param:LOCATION}/channels/${param:EVENTARC_CHANNEL_NAME}