【发布时间】:2017-11-16 19:46:24
【问题描述】:
在 Cloud Firestore 中,我尝试创建函数触发器,但遇到了一些问题。
我希望 Cloud Firestore 函数响应此 Firebase 实时数据库位置的写入:
"VISITORS_PRESENCE" : {
"8PICNP6JBTJDFGiBZYsT" : { // House for sale
"3b1874ec-02f8-4004-817d-a3c44877473c" : { // The user Id
"applicationId" : "3b1874ec-02f8-4004-817d-a3c44877473c",
"last_changed" : 1510859721293,
"state" : "online",
"userId" : "testtest@test,com"
}
}
},
只需将此值/写入复制到 Cloud Firestore 使用此功能: (注意这是基于Cloud Firestore docs functions get-started
exports.onvisitorPresence = functions.database
.ref("/VISITORS_PRESENCE/{uid1}/{uid2}").onWrite((event) => {
// Get the data written to Realtime Database
const eventStatus = event.data.val();
// Then use other event data to create a reference to the
// corresponding Firestore document.
const userStatusFirestoreRef = firestore
.doc(`VISITORS_PRESENCE/${event.params.uid1}/USERS/{event.params.uid2}`);
// It is likely that the Realtime Database change that triggered
// this event has already been overwritten by a fast change in
// online / offline status, so we'll re-read the current data
// and compare the timestamps.
return event.data.ref.once("value").then((statusSnapshot) => {
return statusSnapshot.val();
}).then((status) => {
console.log(status, eventStatus);
// If the current timestamp for this data is newer than
// the data that triggered this event, we exit this function.
if (status.last_changed > eventStatus.last_changed) return;
// Otherwise, we convert the last_changed field to a Date
eventStatus.last_changed = new Date(eventStatus.last_changed);
// ... and write it to Firestore.
return userStatusFirestoreRef.set(eventStatus);
});
});
在 Cloud Firestore 中,这会产生以下内容:
VISITORS_PRESENCE/8PICNP6JBTJDFGiBZYsT/USERS/{event.params.uid2}/
applicationId "3b1874ec-02f8-4004-817d-a3c44877473c"
last_changed 2017 年 11 月 16 日晚上 8:15:21 UTC+1
状态“在线”
userId "testtest@test,com"
我希望上面的 event.params.uid2 是“3b1874ec-02f8-4004-817d-a3c44877473c”,这是一个用户 ID。
我该怎么做?
【问题讨论】:
标签: android firebase firebase-realtime-database google-cloud-functions google-cloud-firestore