בעזרת Cloud Functions for Firebase, אתם יכולים לטפל באירועים ב-Firebase SQL Connect. בעזרת Cloud Functions אפשר להריץ קוד בצד השרת בתגובה לאירועים, כמו ביצוע מוטציה בשירות SQL Connect. כך אפשר להוסיף לוגיקה בהתאמה אישית בלי לפרוס שרתים משלכם.
תרחישים נפוצים לדוגמה
סנכרון נתונים: שכפול או סנכרון של נתונים עם מערכות אחרות (כמו Cloud Firestore, BigQuery או ממשקי API חיצוניים) אחרי שמתרחשת מוטציה.
תהליכי עבודה אסינכרוניים: הפעלת תהליכים ארוכים, כמו עיבוד תמונות או צבירת נתונים, אחרי שינוי במסד הנתונים.
מעורבות משתמשים: שליחת אימיילים או התראות Cloud Messaging למשתמשים אחרי אירוע מוטציה ספציפי באפליקציה, כמו יצירת חשבון.
הפעלת פונקציה במוטציה של SQL Connect
אפשר להפעיל פונקציה בכל פעם שמתבצעת מוטציה של SQL Connect באמצעות הגורם המטפל באירועים onMutationExecuted. הטריגר הזה מופעל כשמתבצעת מוטציה.
פונקציה בסיסית של אירוע Mutation
הדוגמה הבסיסית הבאה היא פונקציה שמתעדת ביומן את הפרטים של כל מוטציה שבוצעה בשירות SQL Connect:
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)
כשמפעילים טריגר על כל המוטציות בפרויקט, אסור לבצע מוטציות ב-handler של הטריגר, אחרת תגרמו ללולאה אינסופית. אם רוצים לבצע שינויים בטריגר של אירוע, צריך להשתמש באפשרויות הסינון שמתוארות בהמשך, ולוודא שהשינוי לא מפעיל את עצמו.
הגדרת המיקום של הפונקציה
כדי שאירועים יפעילו את הפונקציה, מיקום הפונקציה צריך להתאים למיקום השירות של SQL Connect. כברירת מחדל, אזור הפונקציה הוא 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
סינון אירועים
אפשר להגדיר את ה-handler של onMutationExecuted עם אפשרויות לסינון אירועים על סמך מאפיינים ספציפיים. האפשרות הזו שימושית כשרוצים להפעיל את הפונקציה רק למוטציות מסוימות.
אפשר לסנן לפי service, connector ו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)
תווים כלליים לחיפוש וקבוצות לחילוץ
אתם יכולים להשתמש בתווים כלליים לחיפוש ובקבוצות לחילוץ כדי לסנן את הטריגרים לפי כמה ערכים. כל הקבוצות שצולמו זמינות לשימוש ב-event.params. מידע נוסף זמין במאמר הסבר על תבניות נתיבים.
דוגמאות:
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
גישה לפרטי אימות המשתמשים
אתם יכולים לגשת לפרטי האימות של המשתמש שהפעיל את האירוע. למידע נוסף על הנתונים שזמינים בהקשר לצורכי אימות, ראו הקשר לצורכי אימות.
בדוגמה הבאה אפשר לראות איך לאחזר את פרטי האימות:
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
סוג האימות ומזהה האימות יאוכלסו באופן הבא:
| המוטציה הופעלה על ידי | authtype | authid |
|---|---|---|
| משתמש קצה מאומת | app_user |
מזהה ייחודי של אסימון Firebase Auth |
| משתמש קצה לא מאומת | unauthenticated |
ריק |
| SDK לאדמינים שמתחזה למשתמש קצה | app_user
|
מזהה ייחודי של אסימון Firebase Auth של המשתמש שהתחזו אליו |
| בקשה לא מאומתת שמתחזה ל-SDK לאדמינים | unauthenticated |
ריק |
| SDK לאדמינים עם הרשאות מלאות | admin |
ריק |
גישה לנתוני אירועים
האובייקט CloudEvent שמועבר לפונקציה מכיל מידע על האירוע שהפעיל אותה.
מאפייני האירוע
| מאפיין | סוג | תיאור |
|---|---|---|
id |
string |
מזהה ייחודי של האירוע. |
source
|
string
|
משאב המחבר שיצר את האירוע (לדוגמה, //firebasedataconnect.googleapis.com/projects/*/locations/*/services/*/connectors/*). |
specversion |
string |
גרסת המפרט של CloudEvents (למשל, "1.0"). |
type |
string |
סוג האירוע: google.firebase.dataconnect.connector.v1.mutationExecuted. |
time |
string |
חותמת הזמן (בפורמט ISO 8601) של מועד יצירת האירוע. |
subject |
string |
זה שינוי אופציונלי. מידע נוסף על ההקשר של האירוע, כמו שם הפעולה. |
params |
object |
מפה של תבניות נתיבים שתועדו. |
authType |
string |
טיפוסים בני מנייה (enum) שמייצגים את סוג הישות המורשית שהפעילה את האירוע. |
authId |
string |
מזהה ייחודי של חשבון המשתמש שהפעיל את האירוע. |
data |
MutationEventData |
המטען הייעודי של האירוע SQL Connect. עיינו בקטע הבא. |
מטען ייעודי (payload) של נתונים
האובייקט MutationEventData מכיל את המטען הייעודי (payload) של האירוע 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: אובייקט שמכיל את המשתנים שהועברו למוטציה. -
payload.data: אובייקט שמכיל את הנתונים שהוחזרו על ידי המוטציה. -
payload.errors: מערך של שגיאות שהתרחשו במהלך ביצוע המוטציה. אם המוטציה הצליחה, המערך הזה יהיה ריק.
דוגמה
כך ניגשים למשתני המוטציה ולנתונים שמוחזרים:
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
שימו לב שבניגוד לטריגרים אחרים של מסדי נתונים, כמו Cloud Firestore או Realtime Database, האירוע SQL Connect לא מספק תמונת מצב של הנתונים "לפני". מכיוון ש-SQL Connect מעביר בקשות דרך שרת proxy למסד הנתונים הבסיסי, אי אפשר לקבל את תמונת המצב של הנתונים "לפני" באופן טרנזקציונלי. במקום זאת, יש לכם גישה לארגומנטים שנשלחו למוטציה ולנתונים שהיא החזירה.
אחת מההשלכות של זה היא שאי אפשר להשתמש באסטרטגיה של השוואה בין תמונות מצב "לפני" ו "אחרי" כדי להימנע מלולאות אינסופיות, שבהן טריגר של אירוע מפעיל את אותו אירוע. אם אתם חייבים לבצע שינוי מפונקציה שמופעלת על ידי אירוע Mutation, השתמשו במסנני אירועים וודאו שאף שינוי לא יכול להפעיל את עצמו, אפילו באופן עקיף.