javascript - Cloud Functions:检查 Firestore 中的用户文档中是否存在电子邮件不起作用
问题描述
我有一个向用户添加管理员权限的云功能。我让它工作了,但是当我尝试添加一层错误处理时(这样当传入不是注册用户的电子邮件时不会发生异常)我没有让它工作,并且在刮擦之后我的头好几个小时我仍然无法弄清楚。
发生的事情是这段代码总是 return null
,我认为这可能与checkIfUserWithEmailExists is never turn 的结果有关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;
}
});
}
解决方案
您没有正确等待检查功能中的承诺。尝试这个:
//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()
所以我尽量避免这样做。
推荐阅读
- mule - 从 Mule Dataweave 过滤 Json 数组
- python - “ImageField”字段中的默认图像 - Django
- azure - 对如何在 Blazor App 中从 B2C 获取访问令牌感到困惑
- spring - 每当 Spring Integration Poller 触发时写入日志
- asp.net - 部署到本地 IIS 服务器时找不到 /signalr/hubs 404,适用于 IIS express + signalr 1.0
- recursion - 如何在序言中返回一个数字?
- python - python检查字典值是否由字符串列表组成
- python - 如何修复变换透视功能错误地以错误的方向返回图像
- javascript - 引用具有未定义值的变量
- here-api - HERE Maps Mobile SDK 导航和 Xamarin