我从Angular组件创建了一个可调用函数。我的角度组件调用createUser
函数并成功返回userRecord
值。
但是,我想做的是调用另一个名为createUserRecord
的云函数。我并不过分熟悉承诺以及在这种特殊情况下需要返回的内容。
以下是我的两个云功能。在createUserRecord
成功的时候,我怎么去打电话给createUser
?
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);
});
}
如果要在创建用户时在Firestore中创建记录,则可以在独特的云功能中执行此操作。以下代码将完成这一操作,假设您要写入users
Firestore集合。
const FieldValue = require('firebase-admin').firestore.FieldValue;
...
export const createUser = functions.https.onCall((data, context) => {
console.log('data = ', data);
return admin
.auth()
.createUser({
email: data.email,
password: data.password
})
.then(userRecord => {
return admin.firestore().collection('users')
.doc(userRecord.uid)
.set({
email: userRecord.displayName,
createdAt: FieldValue.serverTimestamp(),
nickname: 'bubba'
});
})
.then(() => {
return {
result: 'Success'
};
})
.catch(error => {
//Look at the documentation for Callable Cloud Functions to adapt this part:
//https://firebase.google.com/docs/functions/callable?authuser=0
});
});
“有什么特别的理由不在CF中链接功能吗?” ?
正如documentation中所解释的那样,“云函数可以与特定触发器相关联”。您可以通过创建相应的触发器来“链接”云功能,例如,在一个CF(例如,可调用函数)中在Firestore中创建文档,这将触发另一个响应Firestore触发器的CF.话虽如此,在大多数情况下,您可以通过链接承诺而不是链接云功能来满足独特云功能中的大量需求。
最后,我不建议在云功能中调用HTTP云功能,因为(恕我直言)HTTP云功能更多的设计是由外部消费者调用(我甚至不知道这是否有效)。
让Firebasers就此发表意见会很有趣!