NodeJS firebase admin sdk创建新用户

vi4fp9gy  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(115)

在我的crud项目中,管理员在docs中添加用户,以及在auth中通过普通sdk将替换当前用户,所以我尝试了admin sdk,但编写云函数和调用变得复杂,因为我是firebase的新手。我得到了这个从同胞stackoverflow的线程修改了我的方便,但似乎不工作。
我使用firebase serve在本地部署了函数

云函数

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.createUser = functions.firestore
.document('Teamchers/{userId}')
.onCreate(async (snap, context) => {
    const userId = context.params.userId;
    const newUser = await admin.auth().createUser({
        disabled: false,
        username: snap.get('UserName'),
        email: snap.get('email'),
        password: snap.get('password'),
        subjectname: snap.get('subjectname')
    });
  
    return admin.firestore().collection('Teamchers').doc(userId).delete();
});

字符串
称之为

const createUser = firebase.functions().httpsCallable('createUser');

  const handleadd = async (e) =>{
    e.preventDefault();
    try{
      createUser({userData: data}).then(result => {
        console.log(data);
    });
      addDoc(collection(db, "Courses" , "Teachers", data.subjectname ), {
        ...data,
        timestamp: serverTimestamp(),
        
      });
      alert("Faculty added succesfully")
    } catch (e){
      console.log(e.message)
    }
  }

e5njpo68

e5njpo681#

除了coderpolo和Frank提到的潜在错别字之外,你的代码中还有其他几个错误:

1. JS SDK版本混淆

看起来你把JS SDK V9语法和JS SDK V8语法搞混了。
在前端定义Callable Cloud Function是V8语法:

const createUser = firebase.functions().httpsCallable('createUser');

字符串
而做addDoc(collection(...))是V9语法。
你必须选择一个版本的JS SDK并统一你的代码(参见下面的V9示例,#3)。

2.云函数定义错误

定义你的函数:

exports.createUser = functions.firestore
.document('Teamchers/{userId}')
.onCreate(async (snap, context) => {..})


不是云函数的定义方式。
使用onCreate(),您定义了一个background triggered Cloud Function,当在Firestore中创建新文档而不是Callable CF时,将触发该background triggered Cloud Function
您需要按如下方式调整它:

exports.createUser = functions.https.onCall((data, context) => {

    try {
        // ....
        // Return data that can be JSON encoded
    } catch (e) {
        console.log(e.message)
        // !!!! See the doc: https://firebase.google.com/docs/functions/callable#handle_errors
    }
});

3.使用await,因为您的handleadd()函数是async

这不是严格意义上的错误,但您应该避免同时使用then()async/await
我将其重构如下(V9语法):

import { getFunctions, httpsCallable } from "firebase/functions";

const functions = getFunctions();
const createUser = httpsCallable(functions, 'createUser');

const handleadd = async (e) => {
    e.preventDefault();
    try {
        await createUser({ userData: data })
        await addDoc(collection(db, "Courses", "Teachers", data.subjectname), {
            ...data,
            timestamp: serverTimestamp(),

        });
        alert("Faculty added succesfully")
    } catch (e) {
        console.log(e.message)
    }
}

相关问题