gpt4 book ai didi

node.js - 检查 Firebase 用户是否存在而不抛出错误

转载 作者:搜寻专家 更新时间:2023-10-31 23:28:42 26 4
gpt4 key购买 nike

我有一个提供简单消息服务的网站。个人可以为这项服务付费,或者企业可以按月付费,然后免费添加他们的客户/用户。当企业添加客户/用户电子邮件时,会触发以下功能。我正在使用 firebase 函数和 createUser 在我的服务器上创建用户(较少)。但是,有时企业会尝试注册用户,而该用户已经存在。在这种情况下,我想向用户发送一封提醒邮件。

我的代码工作正常,但在我的捕获/错误中有一个链感觉很时髦。是否有另一种方法可以检测电子邮件是否已注册到不会引发错误的 Firebase 帐户?

exports.newUserRegisteredByBusiness = functions.database.ref('users/{uid}/users/invited/{shortEmail}').onWrite( (data, context) => {

//don't run function if data is null
if (!data.after.val()){
console.log('SKIP: newUserRegisteredByBusiness null so skipping')
return null
} else {

let businessUID = context.params.uid
let email = data.after.val()
let shortEmail = context.params.shortEmail
let password // = something I randomly generate

return admin.auth().createUser({ email: email, password: password}).then( (user)=> {

//write new user data
let updates = {}
let userData // = stuff I need for service to run
updates['users/' + user.uid ] = userData;
return admin.database().ref().update(updates)
}).then( () =>{

//email new user about their new account
return emailFunctions.newUserRegisteredByBusiness(email, password)

}).catch( (error) =>{
//if user already exist we will get error here.
if (error.code === 'auth/email-already-exists'){
//email and remind user about account
return emailFunctions.remindUsersAccountWasCreated(email).then( ()=> {
//Once email sends, delete the rtbd invite value that triggered this whole function
//THIS IS WHERE MY CODE FEELS FUNKY! Is it ok to have this chain?
return admin.database().ref('users/' + businessUID + '/users/invited/' + shortEmail).set(null)
})
} else {

//delete the rtbd value that triggered this whole function
return admin.database().ref('users/' + businessUID + '/users/invited/' + shortEmail).set(null)

}


});

}
})

最佳答案

要查找是否已经为给定的电子邮件地址创建了用户帐户,您可以调用 admin.auth().getUserByEmail .

admin.auth().getUserByEmail(email).then(user => { 
// User already exists
}).catch(err => {
if (err.code === 'auth/user-not-found') {
// User doesn't exist yet, create it...
}
})

虽然您仍在使用 catch(),但感觉操作失败的次数要少得多。

关于node.js - 检查 Firebase 用户是否存在而不抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50154977/

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