透過 Cloud Functions,您可以在 Firebase 即時資料庫中處理事件,而不必更新用戶端程式碼。Cloud Functions 可讓您以完整管理權限執行即時資料庫作業,並確保系統會個別處理即時資料庫的各項變更。您可以透過 DataSnapshot
或 Admin SDK 進行 Firebase 即時資料庫變更。
在一般生命週期中,Firebase 即時資料庫函式會執行下列操作:
- 等待特定即時資料庫位置變更。
- 在事件發生並執行其任務時觸發。如需使用範例,請參閱 Cloud Functions 提供哪些功能?一文。
- 接收包含儲存在指定文件中資料快照的資料物件。
觸發即時資料庫函式
使用 functions.database
為即時資料庫事件建立新函式。如要控制函式的觸發時機,請指定其中一個事件處理常式,並指定其用來監聽事件的即時資料庫路徑。
設定事件處理常式
函式可讓您以兩個精細程度處理即時資料庫事件;您可以特別監聽建立、更新或刪除事件,也可以監聽路徑的任何類型變更。Cloud Functions 支援在即時資料庫中使用以下事件處理常式:
onWrite()
:在即時資料庫中建立、更新或刪除資料時觸發。onCreate()
:在即時資料庫中建立新資料時觸發。onUpdate()
:在即時資料庫中更新資料時觸發。onDelete()
:從即時資料庫刪除資料時觸發。
指定執行個體和路徑
如要控制函式的觸發時機和位置,請呼叫 ref(path)
來指定路徑,並視需要使用 instance('INSTANCE_NAME')
指定即時資料庫執行個體。如果未指定執行個體,函式會部署至 Firebase 專案的預設即時資料庫執行個體。例如:
- 預設即時資料庫執行個體:
functions.database.ref('/foo/bar')
- 執行個體名稱為「my-app-db-2」:
functions.database.instance('my-app-db-2').ref('/foo/bar')
這些方法可引導您的函式處理即時資料庫執行個體中特定路徑的寫入作業。路徑規格會比對涉及路徑的「所有」寫入作業,包括在其下方任何位置發生的寫入。如果您將函式的路徑設為 /foo/bar
,它就會比對這兩個位置的事件:
/foo/bar
/foo/bar/baz/really/deep/path
無論是哪一種情況,Firebase 都會解讀事件在 /foo/bar
發生,而事件資料會包含 /foo/bar
中的新舊資料。如果事件資料可能較大,請考慮在更深的路徑中使用多個函式,而非靠近資料庫根目錄的單一函式。如要獲得最佳效能,請僅要求可能的最深層級資料。
您可以在路徑元件前後加上大括號,將路徑元件指定為萬用字元;ref('foo/{bar}')
會與 /foo
的任何子項相符。這些萬用字元路徑元件的值可在函式的 EventContext.params
物件中找到。在這個範例中,值可做為 context.params.bar
。
使用萬用字元的路徑可以與單一寫入作業中的多個事件進行比對。將
{
"foo": {
"hello": "world",
"firebase": "functions"
}
}
會比對路徑 "/foo/{bar}"
兩次:一次與 "hello": "world"
比對,第二次與 "firebase": "functions"
相符。
處理事件資料
處理即時資料庫事件時,傳回的資料物件會是 DataSnapshot
。如果是 onWrite
或 onUpdate
事件,第一個參數是 Change
物件,內含兩個快照,代表觸發事件前後的資料狀態。對於 onCreate
和 onDelete
事件,傳回的資料物件是建立或刪除資料的快照。
在這個範例中,函式會擷取指定路徑的快照,將該位置的字串轉換為大寫,然後將修改的字串寫入資料庫:
// Listens for new messages added to /messages/:pushId/original and creates an // uppercase version of the message to /messages/:pushId/uppercase exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') .onCreate((snapshot, context) => { // Grab the current value of what was written to the Realtime Database. const original = snapshot.val(); functions.logger.log('Uppercasing', context.params.pushId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to the Firebase Realtime Database. // Setting an "uppercase" sibling in the Realtime Database returns a Promise. return snapshot.ref.parent.child('uppercase').set(uppercase); });
存取使用者驗證資訊
在 EventContext.auth
和 EventContext.authType
中,您可以針對觸發函式的使用者存取使用者資訊,包括權限。這在強制執行安全性規則時相當實用,可讓函式根據使用者的權限等級完成不同的作業:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.simpleDbFunction = functions.database.ref('/path')
.onCreate((snap, context) => {
if (context.authType === 'ADMIN') {
// do something
} else if (context.authType === 'USER') {
console.log(snap.val(), 'written by', context.auth.uid);
}
});
此外,您也可以利用使用者驗證資訊來代表使用者「模擬」使用者並執行寫入作業。請務必刪除應用程式執行個體 (如下所示),以免並行問題:
exports.impersonateMakeUpperCase = functions.database.ref('/messages/{pushId}/original')
.onCreate((snap, context) => {
const appOptions = JSON.parse(process.env.FIREBASE_CONFIG);
appOptions.databaseAuthVariableOverride = context.auth;
const app = admin.initializeApp(appOptions, 'app');
const uppercase = snap.val().toUpperCase();
const ref = snap.ref.parent.child('uppercase');
const deleteApp = () => app.delete().catch(() => null);
return app.database().ref(ref).set(uppercase).then(res => {
// Deleting the app is necessary for preventing concurrency leaks
return deleteApp().then(() => res);
}).catch(err => {
return deleteApp().then(() => Promise.reject(err));
});
});
讀取先前的值
Change
物件提供 before
屬性,可讓您在事件「之前」查看已儲存至即時資料庫的內容。before
屬性會傳回 DataSnapshot
,其中所有方法 (例如 val()
和 exists()
) 都會參照先前的值。您可以使用原始 DataSnapshot
或讀取 after
屬性再次讀取新值。任何 Change
上的這個屬性都是另一個 DataSnapshot
,代表事件發生「之後」資料的狀態。
例如,before
屬性可用於確保函式在首次建立時只有大寫:
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onWrite((change, context) => {
// Only edit data when it is first created.
if (change.before.exists()) {
return null;
}
// Exit when the data is deleted.
if (!change.after.exists()) {
return null;
}
// Grab the current value of what was written to the Realtime Database.
const original = change.after.val();
console.log('Uppercasing', context.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return change.after.ref.parent.child('uppercase').set(uppercase);
});