Mở rộng SQL Connect bằng Cloud Functions

Với Cloud Functions for Firebase, bạn có thể xử lý các sự kiện trong Firebase SQL Connect. Cloud Functions cho phép bạn chạy mã phía máy chủ để phản hồi các sự kiện, chẳng hạn như việc thực thi một đột biến trong dịch vụ SQL Connect của bạn. Điều này cho phép bạn thêm logic tuỳ chỉnh mà không cần triển khai máy chủ của riêng mình.

Các trường hợp sử dụng phổ biến

  • Đồng bộ hoá dữ liệu: Sao chép hoặc đồng bộ hoá dữ liệu với các hệ thống khác (như Cloud Firestore, BigQuery hoặc API bên ngoài) sau khi xảy ra đột biến.

  • Quy trình làm việc không đồng bộ: Bắt đầu các quy trình chạy trong thời gian dài, chẳng hạn như xử lý hình ảnh hoặc tổng hợp dữ liệu, sau khi thay đổi cơ sở dữ liệu.

  • Mức độ tương tác của người dùng: Gửi email hoặc thông báo Cloud Messaging cho người dùng sau một sự kiện biến đổi cụ thể trong ứng dụng của bạn, chẳng hạn như tạo tài khoản.

Kích hoạt một hàm khi có thay đổi về SQL Connect

Bạn có thể kích hoạt một hàm bất cứ khi nào một đột biến SQL Connect được thực thi bằng trình xử lý sự kiện onMutationExecuted. Điều kiện kích hoạt này xảy ra khi thực thi một mutation.

Một hàm sự kiện biến đổi cơ bản

Ví dụ cơ bản sau đây là một hàm ghi lại thông tin chi tiết về mọi đột biến được thực thi trong dịch vụ SQL Connect của bạn:

Node.js

import { onMutationExecuted } from "firebase-functions/dataconnect";
import { logger } from "firebase-functions";

export const logMutation = onMutationExecuted(
  {
    /* Trigger on all mutations, spanning all services and connectors
       in us-central1 */
  },
  (event) => {
    logger.info("A mutation was executed!", {
      data: event.data,
    });
  }
);

Python

from firebase_functions import dataconnect_fn, logger

@dataconnect_fn.on_mutation_executed()
def log_mutation(event: dataconnect_fn.Event):
  logger.info("A mutation was executed!", event.data)

Khi kích hoạt tất cả các đột biến trong dự án, bạn không được thực hiện bất kỳ đột biến nào trong trình xử lý điều kiện kích hoạt, nếu không bạn sẽ gây ra vòng lặp vô hạn. Nếu bạn muốn thực hiện các đột biến trong một trình kích hoạt sự kiện, hãy sử dụng các tuỳ chọn lọc được mô tả bên dưới và lưu ý rằng đột biến không tự kích hoạt.

Đặt vị trí hàm

Vị trí hàm phải khớp với SQL Connect vị trí dịch vụ để các sự kiện kích hoạt hàm. Theo mặc định, khu vực của hàm là us-central1.

Node.js

import { onMutationExecuted } from "firebase-functions/dataconnect";

export const onMutationRegionOption = onMutationExecuted(
  {
    region: "europe-west1"  // Set if SQL Connect service location is not us-central1
  },
  (event) => { /* ... */ }
);

Python

@dataconnect_fn.on_mutation_executed(
  region="europe-west1"  # Set if SQL Connect service location is not us-central1
)
def mutation_executed_handler_region_option(event: dataconnect_fn.Event):
  pass

Lọc sự kiện

Bạn có thể định cấu hình trình xử lý onMutationExecuted bằng các tuỳ chọn để lọc sự kiện dựa trên các thuộc tính cụ thể. Điều này rất hữu ích khi bạn chỉ muốn kích hoạt hàm cho một số đột biến nhất định.

Bạn có thể lọc theo service, connector và operation:

Node.js

import { onMutationExecuted } from "firebase-functions/dataconnect";
import { logger } from "firebase-functions";

// Trigger this function only for the CreateUser mutation
// in the users connector of the myAppService service.
export const onUserCreate = onMutationExecuted(
  {
    service: "myAppService",
    connector: "users",
    operation: "CreateUser",
  },
  (event) => {
    logger.info("A new user was created!", event.data);
    // Add logic here: for example, sending a welcome email.
  }
);

Python

from firebase_functions import dataconnect_fn, logger

@dataconnect_fn.on_mutation_executed(
  service="myAppService",
  connector="users",
  operation="CreateUser"
):
def on_user_create(event: dataconnect_fn.Event):
  logger.info("A new user was created!", event.data)

Ký tự đại diện và nhóm thu thập

Bạn có thể sử dụng ký tự đại diện và nhóm thu thập để lọc trình kích hoạt theo nhiều giá trị. Mọi nhóm ảnh chụp đều có trong event.params để bạn sử dụng. Hãy xem phần Tìm hiểu về mẫu đường dẫn để biết thêm thông tin.

Ví dụ:

Node.js

import { onMutationExecuted } from "firebase-functions/dataconnect";

// Trigger on all operations that match the pattern `User*`, on any service and
// connector.
export const onMutationWildcards = onMutationExecuted(
  {
    operation: "User*",
  },
  (event) => {}
);

// Trigger on all operations that match the pattern `User*`, on any service and
// connector. Capture the operation name in the variable `op`.
export const onMutationCaptureWildcards = onMutationExecuted(
  {
    operation: "{op=User*}",
  },
  (event) => {
    // `event.params.op` contains the operation name.
  }
);

// Trigger on all operations on the service `myAppService`. Capture the
// operation name in the variable `operation`.
export const onMutationCaptures = onMutationExecuted(
  {
    service: "myAppService",
    operation: "{operation}",
  },
  (event) => {
    // `event.params.operation` contains the operation name.
  }
);

Python

from firebase_functions import dataconnect_fn

# Trigger on all operations that match the pattern `User*`, on any service and
# connector.
@dataconnect_fn.on_mutation_executed(
  operation="User*"
)
def on_mutation_wildcards(event: dataconnect_fn.Event):
  pass

# Trigger on all operations that match the pattern `User*`, on any service and
# connector. Capture the operation name in the variable `op`.
@dataconnect_fn.on_mutation_executed(
  operation="{op=User*}"
)
def on_mutation_capture_wildcards(event: dataconnect_fn.Event):
  # `event.params["op"]` contains the operation name.
  pass

# Trigger on all operations on the service `myAppService`. Capture the
# operation name in the variable `operation`.
@dataconnect_fn.on_mutation_executed(
  service="myAppService",
  operation="{operation}"
)
def on_mutation_captures(event: dataconnect_fn.Event):
  # `event.params["operation"]` contains the operation name.
  pass

Truy cập vào thông tin xác thực người dùng

Bạn có thể truy cập vào thông tin xác thực người dùng về đối tượng chính đã kích hoạt sự kiện. Để biết thêm thông tin về dữ liệu có trong bối cảnh xác thực, hãy xem phần Bối cảnh xác thực.

Ví dụ sau đây minh hoạ cách truy xuất thông tin xác thực:

Node.js

import { onMutationExecuted } from "firebase-functions/dataconnect";

export const onMutation = onMutationExecuted(
  { operation: "MyMutation" },
  (event) => {
    // mutationExecuted event provides authType and authId:
    // event.authType
    // event.authId
  }
);

Python

from firebase_functions import dataconnect_fn

@dataconnect_fn.on_mutation_executed(operation="MyMutation")
def mutation_executed_handler(event: dataconnect_fn.Event):
  # mutationExecuted event provides auth_type and auth_id, which are accessed as follows
  # event.auth_type
  # event.auth_id
  pass

Loại và mã xác thực sẽ được điền như sau:

Thay đổi do authtype authid
Người dùng cuối đã xác thực app_user UID mã thông báo Firebase Auth
Người dùng cuối chưa được xác thực unauthenticated trống
SDK dành cho quản trị viên mạo danh người dùng cuối app_user UID mã thông báo Firebase Auth của người dùng được mạo danh
SDK dành cho quản trị viên mạo danh một yêu cầu chưa được xác thực unauthenticated trống
SDK dành cho quản trị viên có toàn quyền admin trống

Truy cập vào dữ liệu sự kiện

Đối tượng CloudEvent được truyền đến hàm của bạn chứa thông tin về sự kiện đã kích hoạt hàm đó.

Thuộc tính sự kiện

Thuộc tính Loại Mô tả
id string Giá trị nhận dạng riêng biệt của sự kiện.
source string Tài nguyên trình kết nối đã tạo ra sự kiện (ví dụ: //firebasedataconnect.googleapis.com/projects/*/locations/*/services/*/connectors/*).
specversion string Phiên bản quy cách CloudEvents (ví dụ: "1.0").
type string Loại sự kiện: google.firebase.dataconnect.connector.v1.mutationExecuted.
time string Dấu thời gian (định dạng ISO 8601) cho thời điểm sự kiện được tạo.
subject string Không bắt buộc. Thông tin bổ sung về bối cảnh sự kiện, chẳng hạn như tên thao tác.
params object Bản đồ các mẫu đường dẫn đã thu thập.
authType string Một enum đại diện cho loại chủ thể đã kích hoạt sự kiện.
authId string Giá trị nhận dạng riêng biệt của đối tượng chính đã kích hoạt sự kiện.
data MutationEventData Phần tải của sự kiện SQL Connect. Hãy xem phần tiếp theo.

Phần tải dữ liệu

Đối tượng MutationEventData chứa tải trọng của sự kiện SQL Connect:

{
  // ...
  "authType": // ...
  "data": {
    "payload": {
      "variables": {
        "userId": "user123",
        "updateData": {
          "displayName": "New Name"
        }
      },
      "data": {
        "updateUser": {
          "id": "user123",
          "displayName": "New Name",
          "email": "user@example.com"
        }
      },
      "errors": []
    }
  }
}
  • payload.variables: Một đối tượng chứa các biến được truyền đến đột biến.
  • payload.data: Một đối tượng chứa dữ liệu do đột biến trả về.
  • payload.errors: Một mảng gồm mọi lỗi xảy ra trong quá trình thực thi đột biến. Nếu đột biến thành công, mảng này sẽ trống.

Ví dụ

Sau đây là cách bạn có thể truy cập vào các biến đột biến và dữ liệu được trả về:

Node.js

import { onMutationExecuted } from "firebase-functions/dataconnect";
import { logger } from "firebase-functions";

export const processNewUserData = onMutationExecuted(
  {
    "service": "myAppService",
    "connector": "users",
    "operation": "CreateUser",
  },
  (event) => {
    // The variables passed to the mutation
    const mutationVariables = event.data.payload.variables;

    // The data returned by the mutation
    const returnedData = event.data.payload.data;

    logger.info("Processing mutation with variables:", mutationVariables);
    logger.info("Mutation returned:", returnedData);

    // ... your custom logic here
  }
);

Python

from firebase_functions import dataconnect_fn, logger

@dataconnect_fn.on_mutation_executed(
  service="myAppService",
  connector="users",
  operation="CreateUser"
):
def process_new_user_data(event: dataconnect_fn.Event):
  # The variables passed to the mutation
  mutation_vars = event.data.payload.variables
  # The data returned by the mutation
  returned_data = event.data.payload.data

  logger.info("Processing mutation with variables:", mutationVariables)
  logger.info("Mutation returned", returnedData)

  # ... your custom logic here

Xin lưu ý rằng không giống như một số trình kích hoạt cơ sở dữ liệu khác, chẳng hạn như Cloud Firestore hoặc Realtime Database, sự kiện SQL Connect không cung cấp ảnh chụp nhanh "trước" của dữ liệu. Vì SQL Connect uỷ quyền các yêu cầu cho cơ sở dữ liệu cơ bản, nên không thể lấy ảnh chụp nhanh "trước" của dữ liệu theo giao dịch. Thay vào đó, bạn có quyền truy cập vào các đối số được gửi đến đột biến và dữ liệu mà đột biến đó trả về.

Một hệ quả của việc này là bạn không thể sử dụng chiến lược so sánh ảnh chụp nhanh "trước" và "sau" để tránh vòng lặp vô hạn, trong đó một trình kích hoạt sự kiện kích hoạt cùng một sự kiện. Nếu bạn phải thực hiện một sự kiện biến đổi từ một hàm được kích hoạt bởi một sự kiện biến đổi, hãy sử dụng bộ lọc sự kiện và đảm bảo rằng không có sự kiện biến đổi nào có thể tự kích hoạt, ngay cả khi gián tiếp.