**在我的 crud 專案中,管理員在檔案中添加用戶以及通過普通 sdk 在 auth 中添加用戶將替換當前用戶,所以我嘗試了 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)
}
}
uj5u.com熱心網友回復:
除了 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) => {..})
不是您應該定義Callable Cloud 函式的方式。
onCreate()您正在定義一個后臺觸發的云函式,該函式將在 Firestore 中創建新檔案時觸發,而不是 Callable CF。
您需要按如下方式對其進行調整:
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()and 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)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/514821.html
標籤:Google Cloud Collective javascript节点.js反应火力基地谷歌云功能
上一篇:同步JSONuseEffect
