我的用户集合上有一个 onUpdate 触发器,用于更新相应的用户个人资料。
exports.onUpdateUser = functions.firestore.document('/users/{uid}')
.onUpdate((change, context) => {
const { uid } = context.params;
const { email, displayName, photoURL } = change.after.data();
return admin.auth().updateUser(uid, {
email,
displayName,
photoURL
});
});
如果提供的电子邮件已经存在,则触发器可能会引发错误。在这种情况下,我要放弃对用户文档所做的更改,然后让客户端知道该错误。
通过上述实现,文档将成功更新,并且触发器将在客户端不知情的情况下静默引发错误。
我可以更改此行为还是我唯一的选择是实现单独的HTTP云功能来处理用户更新?
答案 0 :(得分:0)
在发生错误的情况下,您可以做的是利用Cloud Function将数据写入/users/{uid}
节点下的特定子节点,并使您的客户端前端侦听该子节点。
Cloud Function代码如下:
exports.onUpdateUser = functions.firestore.document('/users/{uid}')
.onUpdate((change, context) => {
const { uid } = context.params;
const { email, displayName, photoURL } = change.after.data();
return admin.auth().updateUser(uid, {
email,
displayName,
photoURL
})
.catch(error => {
if (error == "auth/email-already-exists") {
return admin.database().ref('/users/' + uid).set({updateError: true})
.catch(error => {
console.log("Error reporting email error");
return false;
});
} else {
console.log("Error updating user:", error);
return false;
}
});
});
在您的前端收听/users/{uid}/updateError
节点,并在写入新值的情况下显示警报/消息。确切的侦听器语法取决于您的前端技术(Web应用程序?Android应用程序?iOS应用程序?)。
请注意,在Cloud Function中,您可以利用admin.auth().updateUser()
方法的错误管理以及它返回特定代码的事实。
请参阅https://firebase.google.com/docs/auth/admin/errors
和https://firebase.google.com/docs/auth/admin/manage-users#update_a_user,其中指出:
如果提供的uid与现有用户不对应,则 提供的电子邮件或电话号码已被现有用户使用, 或由于其他任何原因而无法更新用户,上述方法 失败并显示错误。