gpt4 book ai didi

javascript - 云函数: Checking if email exists in users document in Firestore not working

转载 作者:行者123 更新时间:2023-12-02 22:04:04 25 4
gpt4 key购买 nike

我有一个云功能,它正在向用户添加管理员权限。我让它工作,但是当我尝试添加一层错误处理(以便在传递不是注册用户的电子邮件时不会发生异常)时,我没有让它工作,并且在抓取之后我思考了几个小时,仍然无法弄清楚。

发生的情况是这段代码总是返回null,我认为这可能与checkIfUserWithEmailExists的结果永远不会变成true.

这是我创建的代码:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

exports.addAdmin = functions.https.onCall(async (data, context) => {
const result = await checkIfUserWithEmailExists(data.email);
if (result === true) {
if (context.auth.token.admin !== true) {
return {
error: "Request not authorized. User must be an admin to fulfill"
};
}
const email_1 = data.email;
return grantAdminRole(email_1).then(() => {
return {
result: `Request fulfilled! ${email_1} is now an admin`
};
});
} else {
return {
error: "No user with this email was found"
};
}
});

async function grantAdminRole(email_2) {
// get user and add custom claim (admin)
const user = await admin.auth().getUserByEmail(email_2);
if (user.customClaims && user.customClaims.admin === true) {
return;
}
return admin.auth().setCustomUserClaims(user.uid, {
admin: true
});
}

//Checks that the email passed in is an existing user
async function checkIfUserWithEmailExists(email) {
const userCollectionRef = admin.firestore().collection("users");
userCollectionRef
.where("email", "==", email)
.get()
.then(querySnapshot => {
if (querySnapshot.size === 1) {
return true;
} else {
return false;
}
});
}

最佳答案

您没有正确等待检查函数中的 promise 。试试这个:

//Checks that the email passed in is an existing user
async function checkIfUserWithEmailExists(email) {
const userCollectionRef = admin.firestore().collection("users");
const querySnapshot = await userCollectionRef
.where("email", "==", email)
.get();

return querySnapshot.size >= 1;
}

一般来说,将 async/await 与 Promise .then() 结合起来可能会令人困惑,所以我尽量避免这样做。

关于javascript - 云函数: Checking if email exists in users document in Firestore not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59775000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com