【发布时间】:2019-09-14 15:44:01
【问题描述】:
我从我的 Angular 组件创建了一个可调用函数。我的角度组件调用createUser 函数并成功返回userRecord 值。
但是,我想做的是调用另一个名为 createUserRecord 的云函数。我不太熟悉 Promise 以及在这种特定情况下需要返回什么。
以下是我的两个云功能。在createUser 成功后,我将如何调用createUserRecord?
export const createUser = functions.https.onCall(async (data, context) => {
console.log('data = ', data);
return admin.auth().createUser({
email: data.email,
password: data.password,
}).then(function (userRecord) {
return userRecord
})
.catch(function (error) {
return error;
console.log('Error creating new user:', error);
});
});
export const createUserRecord = functions.auth.user().onCreate((user, context) => {
const userRef = db.doc(`users/${user.uid}`);
return userRef.set({
email: user.displayName,
createdAt: context.timestamp,
nickname: 'bubba',
})
});
更新
这是我制作的一个版本,其中我将两个函数合并在一起。这确实会产生创建和帐户然后写入 Firestore 的预期结果。但是,由于它没有向客户端返回值,它确实感觉有点“不妥”。
export const createUser = functions.https.onCall(async (data, context) => {
console.log('data = ', data);
return admin.auth().createUser({
email: data.email,
password: data.password,
}).then(function (userRecord) {
const userRef = db.doc(`users/${userRecord.uid}`);
return userRef.set({
email: data.email,
name: data.name,
})
})
.catch(function (error) {
return error;
console.log('Error creating new user:', error);
});
});
角度可调用函数
sanitizedMessage 控制台日志将返回 undefined。
addUser() {
const createUser = firebase.functions().httpsCallable('createUser');
const uniquePassword = this.afs.createId();
createUser({
email: this.userForm.value.email,
password: uniquePassword,
name: this.userForm.value.name,
}).then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
console.log('sanitizedMessage = ', sanitizedMessage);
}).catch((error) => {
var code = error.code;
var message = error.message;
var details = error.details;
console.log('error = ', error);
});
}
【问题讨论】:
-
您不应从一个云函数调用另一个云函数。您在这里的确切用户要求是什么?您想在创建用户时在实时数据库中创建记录吗?您可能可以在一个云函数中涵盖它。
-
嘿@RenaudTarnec - 基本上是的,但在这种情况下它是firestore。我尝试将
return userRef.set方法(来自createUserRecord)移动到createUser函数的.then(function(userRecord)中。那行得通。但感觉很hacky。这真的可以接受吗?有什么特别的理由不在 CF 中链接函数吗? -
@RenaudTarnec - 我在代码中添加了更新来解释上述评论。
-
我刚刚发布了一个答案。告诉我它是如何工作的。
标签: javascript firebase google-cloud-firestore google-cloud-functions