检查 Firebase 用户是否存在而不抛出错误

Check If Firebase User Exist Without Throwing Error

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

我的代码工作正常,但在我的 catch/error 中有一个链感觉很时髦。是否有另一种方法可以检测电子邮件是否已注册到不会引发错误的 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(),但感觉操作失败的次数要少得多。

为避免在 catch 块中进一步实施,您可以将此 Firebase 函数包装到此代码中:

async function checkUserInFirebase(email) {
    return new Promise((resolve) => {
        admin.auth().getUserByEmail(email)
            .then((user) => {
                resolve({ isError: false, doesExist: true, user });
            })
            .catch((err) => {
                resolve({ isError: true, err });
            });
    });
}

...

const rFirebase = await checkUserInFirebase('abc@gmail.com');