【问题标题】:Firebase Cloud Functions - How to call another function and return objectFirebase Cloud Functions - 如何调用另一个函数并返回对象
【发布时间】: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


【解决方案1】:

如果您想在创建用户时在 Firestore 中创建记录,您可以在独特的 Cloud Function 中很好地做到这一点。以下代码可以解决问题,假设您要写入 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 中所述,“云函数可以与特定触发器相关联”。您可以通过创建相应的触发器来“链接”云函数,例如,在 Firestore 中的一个 CF(例如可调用函数)中创建一个文档,这将触发另一个响应 Firestore 触发器的 CF)。 话虽如此,在大多数情况下,通过链接 Promise 而不是链接 Cloud Functions,您可能可以在独特的 Cloud Function 中满足许多需求

最后,我不建议从云函数中调用 HTTP 云函数,因为(恕我直言)HTTP 云函数更适合由外部使用者调用(我什至不知道这是否可行)。

Firebases 对此有意见会很有趣!

【讨论】:

  • 这是一种享受。至少我在第二次尝试时很接近。谢谢你这么棒的回复!
猜你喜欢
  • 1970-01-01
  • 2021-12-16
  • 2018-12-04
  • 1970-01-01
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
相关资源
最近更新 更多