![](/img/trans.png)
[英]How to use firebase cloud functions' firestore.onWrite() in netlify lamda
[英]How to use firebase cloud functions for logic on firestore data
我是使用 firebase 的新手,為了保持數據更安全,我一直在嘗試將一些邏輯從客戶端移動到服務器。
下面是我一直在嘗試使用雲功能的工作客戶端代碼。
const swipeRight = async (cardIndex) => {
// card index is a reference to the card you swiped on
// if the user doesn't exist in the database
if (!profiles[cardIndex]) return;
// userSwiped is the person that the user swiped right on
const userSwiped = profiles[cardIndex];
const userSwipedId = profiles[cardIndex].id;
// adds the userSwipedId to the liked collection of the user
setDoc(doc(db, "user", user.uid, "liked", userSwiped.id), userSwiped);
// this is where we get the users ID
const loggedInProfile = await (
await getDoc(doc(db, "user", user.uid))
).data();
// check if user (convert to firebase cloud function asap)
// start of cloud function
// get a document snapshot if the user ID is in the liked collection of the userSwiped
let isMatch = getDoc(
doc(db, "user", userSwiped.id, "liked", user.uid)
).then((documentSnapshot) => {
if (documentSnapshot.exists()) {
console.log("matched with", userSwiped.displayName);
return true;
} else return false;
});
// end of cloud function
if (isMatch) {
createMatchInDb(user, userSwiped, loggedInProfile);
// navigate to match screen on match
navigation.navigate("Match", {
loggedInProfile,
userSwiped,
});
let isMatch = false;
}
};
以上效果很好。 它從 userSwiped 中獲取喜歡的用戶列表,然后檢查 userSwiping 是否在其中。 雲 function 將返回 true 或 false 並且將對 true 執行操作
對於可能的解決方案,我有兩個想法,但我還不能讓它們發揮作用。
首先
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.checkMatch = functions.firestore
.document("/user/{userSwiped}/liked")
.onUpdate((snap, context) => {
{
// check here whether the userSwiping is present in the userSwiped list of liked users.
}
});
第二
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.checkMatch = functions.firestore
.onCall((data, context) => {
{
// how do I query the database to check if the user swiping
// is present in the userSwiped array of liked users?
}
});
我花了很多時間閱讀文檔,但完全不知道如何從數據庫中實際查詢數據以用於我的邏輯。 返回結果似乎不是問題,但我正在努力建立連接並通過雲功能從數據庫中實際獲取數據。
任何幫助或建議將不勝感激,我已經花了很多時間尋找博客或其他解釋,但在工作測試上有點不足。
謝謝
exports.checkMatch = functions.https.onCall((data, context) => {
const userId = context.auth.uid;
return new Promise((resolve, reject) => {
const db = admin.firestore();
db.collection(`/user/${userId}/liked`)
.get()
.then((snapshot) => {
if (!snapshot.empty) {
resolve({"result": true});
} else {
resolve({"results": false});
}
})
.catch((reason) => {
console.log(
`reason: + ${reason}`
);
reject(reason);
});
});
});
我不確定如何,但我設法幸運地進入了這個可行的解決方案。 我希望這對有一天遇到同樣問題的人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.